My Ruby application processes jobs that each take ~10 seconds to execute. Each job spends a lot of time waiting for IO. I have timers that use simple Time.now comparisons to record how long each stage of the job takes:
def timer
t = Time.now
yield
(Time.now - t).seconds
end
timer do
# IO
end
=> 1.342
Originally, I processed all jobs sequentially, and this was great except that the machine was idle 50% of the time (due to IO).
I shifted to a multithreaded model to recoup some IO time. Now I spawn a new thread for each job, up to a maximum of 10 simultaneous threads. This works great, except that, when a thread gets preempted while running a timer block, the timer keeps “running” while the thread is sleeping, causing the timer to return an artificially inflated number.
What I need is a way to figure out the actual run time of the timer block, ignoring time spent sleeping. Is there a way to achieve this, such as asking Thread.current how much time it’s spent running?
Benchmark does this by measuring both wall-clock time and CPU time.