Skip to content

Instantly share code, notes, and snippets.

@janzikan
Created November 21, 2017 13:32
Show Gist options
  • Save janzikan/362a3555f16d78b7b173f0f820a22ed8 to your computer and use it in GitHub Desktop.
Save janzikan/362a3555f16d78b7b173f0f820a22ed8 to your computer and use it in GitHub Desktop.
Ruby: Measure execution time of your code
def stopwatch(cycles = 1)
cycles = cycles.to_i
return if cycles == 0
start = Time.now.to_f
cycles.times do
yield
end
elapsed_time = Time.now.to_f - start
puts "Total elapsed time: #{elapsed_time}"
puts "Average time: #{elapsed_time / cycles}" if cycles > 1
end
# Run multiple cycles to have more accurate results.
stopwatch(10) do
# Your code.
# sleep(0.1)
end
# Run your code only once.
stopwatch do
# Your code.
# sleep(0.1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment