Monday, June 20, 2011

Converting Ruby Time to Milliseconds

Coming from Java land, I am really used to working in milliseconds and often times I want to time a block of code in milliseconds, so here's how I do it:

start_time = Time.now
# some code to time
end_time = Time.now
duration_in_ms = ((end_time.to_f - start_time.to_f) * 1000.0).to_i

Or to get current time since epoch in milliseconds:

(Time.now.to_f * 1000.0).to_i