Skip to content

Instantly share code, notes, and snippets.

@reu
Created August 18, 2010 14:35
Show Gist options
  • Save reu/534927 to your computer and use it in GitHub Desktop.
Save reu/534927 to your computer and use it in GitHub Desktop.
# Ruby way fail
# Implementation of a simple method to convert seconds to time format (03:44:23)
require "benchmark"
seconds = 45020
hours = seconds / 3600
minutes = seconds / 60 % 60
seconds = seconds % 60
n = 1000000
Benchmark.bm do |b|
# Ruby way
b.report do
n.times { [hours, minutes, seconds].map{ |time| time.to_s.rjust(2, "0") }.join(":") }
end
# Kitten killer way (aka using sprintf)
b.report do
n.times { "%02d:%02d:%02d" % [hours, minutes, seconds] }
end
end
# user system total real
# 4.650000 0.000000 4.650000 ( 4.701532)
# 2.740000 0.000000 2.740000 ( 2.767670)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment