Skip to content

Commit 6a3fe1f

Browse files
committed
Add Benchmark.ms method and enhance realtime with unit parameter
Rails previously included a monkeypatch that added a `ms` method to the Benchmark module to return timing results in milliseconds instead of seconds. This monkeypatch has been deprecated in Rails and will be removed in future versions. ref: rails/rails@4cdf757 This commit adds native support for millisecond timing measurements by adding a new `Benchmark.ms` method that returns elapsed time in milliseconds. For web applications, measuring performance in milliseconds is much more helpful since the majority of operations happen in less than a second. While it's acceptable to display times >1s as "1.2s", showing "0.125s" instead of "125ms" is significantly less readable and intuitive for developers analyzing performance metrics. ```ruby Benchmark.realtime { sleep 0.1 } #=> 0.10023 Benchmark.ms { sleep 0.1 } #=> 100.23 ``` This change provides a clean migration path for Rails applications currently relying on the deprecated monkeypatch while offering enhanced functionality for all benchmark users.
1 parent 4e39de6 commit 6a3fe1f

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)