Created
November 21, 2017 13:32
-
-
Save janzikan/362a3555f16d78b7b173f0f820a22ed8 to your computer and use it in GitHub Desktop.
Ruby: Measure execution time of your code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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