Commit b730244
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:
1. **Enhanced Benchmark.realtime method**: Now accepts an optional `unit`
parameter (defaulting to `:float_second` for backward compatibility)
that leverages `Process.clock_gettime`'s built-in unit support.
2. **New Benchmark.ms method**: A convenience method that returns elapsed
time in milliseconds, equivalent to `realtime(:float_millisecond)`.
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.realtime(:float_millisecond) { sleep 0.1 } #=> 100.23
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.
As an alternative approach, the .realtime method now accepts an optional
unit argument that gets passed directly to Process.clock_gettime, allowing
developers to specify their preferred time unit (:float_second, :float_millisecond,
:float_microsecond, :nanosecond) while maintaining backward compatibility.1 parent 4e39de6 commit b730244
1 file changed
+20
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
314 | 314 | | |
315 | 315 | | |
316 | 316 | | |
317 | | - | |
| 317 | + | |
| 318 | + | |
318 | 319 | | |
319 | 320 | | |
320 | 321 | | |
321 | 322 | | |
322 | | - | |
323 | | - | |
| 323 | + | |
| 324 | + | |
| 325 | + | |
| 326 | + | |
| 327 | + | |
324 | 328 | | |
325 | | - | |
| 329 | + | |
| 330 | + | |
| 331 | + | |
| 332 | + | |
| 333 | + | |
| 334 | + | |
| 335 | + | |
| 336 | + | |
| 337 | + | |
| 338 | + | |
| 339 | + | |
| 340 | + | |
326 | 341 | | |
327 | 342 | | |
328 | | - | |
| 343 | + | |
329 | 344 | | |
330 | 345 | | |
331 | 346 | | |
| |||
0 commit comments