Skip to content

Commit fc27ad1

Browse files
authored
Merge pull request #38 from Shopify/add-ms-function-and-pass-unit-arg-to-realtime
Add Benchmark.ms method and enhance realtime with unit parameter
2 parents 4e39de6 + 6a3fe1f commit fc27ad1

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

lib/benchmark.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,20 @@ def realtime # :yield:
325325
Process.clock_gettime(Process::CLOCK_MONOTONIC) - r0
326326
end
327327

328-
module_function :benchmark, :measure, :realtime, :bm, :bmbm
328+
#
329+
# Returns the elapsed real time used to execute the given block.
330+
# The unit of time is milliseconds.
331+
#
332+
# Benchmark.ms { "a" * 1_000_000_000 }
333+
# #=> 509.8029999935534
334+
#
335+
def ms # :yield:
336+
r0 = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
337+
yield
338+
Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - r0
339+
end
340+
341+
module_function :benchmark, :measure, :realtime, :ms, :bm, :bmbm
329342

330343
#
331344
# A Job is a sequence of labelled blocks to be processed by the

test/benchmark/test_benchmark.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,12 @@ def test_realtime_output
156156
assert_operator sleeptime, :<, realtime
157157
end
158158

159+
def test_ms_output
160+
sleeptime = 1.0
161+
ms_time = Benchmark.ms { sleep sleeptime }
162+
assert_operator sleeptime * 1000, :<, ms_time
163+
end
164+
159165
# Test that `to_h` returns a hash with the expected data.
160166
def test_tms_to_h
161167
tms = Benchmark::Tms.new(1.1, 2.2, 3.3, 4.4, 5.5, 'my label')

0 commit comments

Comments
 (0)