Sha256: 4975b6e07650dca60de4918965bff83eb8f5298c0fefd9bfbcacbf0ef48841e8

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

module Vedeu

  module Logging

    # Measure the duration. Used for debugging.
    #
    class Timer

      class << self

        # Measure the execution time of the code in the given block.
        #
        # @example
        #   Vedeu.timer 'message' do
        #     # ... code to be measured
        #   end
        #
        # @param message [String]
        # @param block [Proc]
        # @return [void] The return value of the executed block.
        def timer(message = '', &block)
          new(message).measure(&block)
        end

      end # Eigenclass

      # Returns a new instance of Vedeu::Logging::Timer.
      #
      # @param message [String]
      # @return [Vedeu::Logging::Timer]
      def initialize(message = '')
        @message = message
        @started = Time.now.to_f
      end

      # Write an entry to the log file stating how long a section of
      # code took in milliseconds. Useful for debugging performance.
      #
      # @return [void] The return value of the executed block.
      def measure
        work = yield

        Vedeu.log(type: :timer, message: "#{message} took #{elapsed}ms.")

        work
      end

      protected

      # @!attribute [r] started
      # @return [Time]
      attr_reader :started

      # @!attribute [r] message
      # @return [String]
      attr_reader :message

      # Returns the elapsed time in milliseconds with 3 decimal
      # places.
      #
      # @return [Float]
      def elapsed
        ((Time.now.to_f - started) * 1000).round(3)
      end

    end # Timer

  end # Logging

  # Measure the execution time of the code in the given block.
  #
  # @example
  #   Vedeu.timer do
  #     # ... some code here ...
  #   end
  #
  # @!method timer
  #   @see Vedeu::Logging::Timer.timer
  def_delegators Vedeu::Logging::Timer, :timer

end # Vedeu

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
vedeu-0.6.21 lib/vedeu/logging/timer.rb