Sha256: 3f9e46bbd86bb357efd8b9aa9d418399c2718069d39f8dc39b7ea93e7bd7f488

Contents?: true

Size: 1.67 KB

Versions: 7

Compression:

Stored size: 1.67 KB

Contents

# Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

module Contrast
  module Utils
    # Timer is class that can track state about when an event starts and how long it takes
    # Also containes utility methods to get time values in milliseconds
    class Timer
      attr_reader :start_at, :start_ms, :events

      def initialize time = Time.now
        @start_at = time
        @start_ms = (@start_at.to_f * 1000).to_i
        @events = {}
      end

      def elapsed label
        before = Time.now
        result = yield if block_given?
        events[label.to_s] = ((Time.now - before) * 1000).to_i
        result
      end

      def ms key
        events[key.to_s] || 0
      end

      def abs key
        start_ms + (events[key.to_s] || 0)
      end

      def to_s
        pairs = events.to_a.map { |pair| "#{ pair[0] }=#{ pair[1] }ms" }
        start_at.strftime('%Y-%m-%d %H:%M:%S.%L') + pairs.join(Contrast::Utils::ObjectShare::SPACE)
      end

      def diff_s start_ms
        (now_ms - start_ms) / 1000
      end

      def now_ms
        (Time.now.to_f * 1000).to_i
      end

      def self.now_ms
        (Time.now.to_f * 1000).to_i
      end

      def self.earliest lhs, rhs
        if lhs && rhs
          [lhs, rhs].min
        elsif lhs
          lhs
        else
          rhs
        end
      end

      def self.latest lhs, rhs
        if lhs && rhs
          [lhs, rhs].max
        elsif lhs
          lhs
        else
          rhs
        end
      end

      def now_sec
        now_ms / 1000
      end

      def elapsed_ms
        now_ms - start_ms
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
contrast-agent-3.10.2 lib/contrast/utils/timer.rb
contrast-agent-3.10.1 lib/contrast/utils/timer.rb
contrast-agent-3.10.0 lib/contrast/utils/timer.rb
contrast-agent-3.9.1 lib/contrast/utils/timer.rb
contrast-agent-3.9.0 lib/contrast/utils/timer.rb
contrast-agent-3.8.5 lib/contrast/utils/timer.rb
contrast-agent-3.8.4 lib/contrast/utils/timer.rb