Hitimes are upon us (2008-09-14)
Saturday afternoon at the Lone Star Ruby Conf I was discussing something, I forget exactly what, with Bruce and he mentioned that he was looking for a really fast way to measure elapsed time of a piece of code.
The naive approach would be call Time.now
before and after the call, or maybe use the Time.elapse method from Facets. Both of those approaches are perfectly acceptable, and return results down to the µsecond. Can we do better? Yes.
We have a goal of being faster than 2 successive Time.now
calls. Each operating system has a different way accessing a high-resolution timer.
- Unixes - the POSIX calls to
clock_gettime()
- OS X -
UpTime()
- Windows -
QueryPerformanceCounter()
Unify the C level interface to all of those, wrap it up in a Ruby extension and the result is the just-released Hitimes, a high-resolution timer library in Ruby for when you want to do measuring at the nanosecond level.
gem install hitimes
The simplest and lightest weight way to use the library is via the Interval
class. This does one really simple thing. It measures an interval of time. You can measure code in a block:
require 'hitimes' require 'open-uri' duration = Hitimes::Interval.measure do bruce = open("http://www.codefluency.com/").read end puts duration # => 0.261841618
Or measure a particular piece of code for performance:
interval = Hitimes::Interval.new # do something interval.start # some code to measure duration = interval.stop
There are other approaches using Interval
, and a Timer class for measuring series of intervals and reporting statistics.