Skip to content

Instantly share code, notes, and snippets.

@cch1
Created January 15, 2010 16:37
Show Gist options
  • Save cch1/278185 to your computer and use it in GitHub Desktop.
Save cch1/278185 to your computer and use it in GitHub Desktop.
require 'benchmark'
ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
FAST_ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(?:\.(\d+))?\z/
COUNT = 1000000
SRAND = 1455677931
DATETIME_STRING = "2010-01-12 12:34:56.%6.6i"
Benchmark.bm do |bench|
f = bench.report("Fast") do
srand(SRAND)
COUNT.times do
i0 = rand(1000000)
str = sprintf(DATETIME_STRING, i0)
usec = FAST_ISO_DATETIME.match(str)[7].to_i
# raise unless usec == i0
end
end
s = bench.report("Slow") do
srand(SRAND)
COUNT.times do
i0 = rand(1000000)
str = sprintf(DATETIME_STRING, i0)
usec = (ISO_DATETIME.match(str)[7].to_f * 1_000_000).to_i
# usec = (ISO_DATETIME.match(str)[7].to_f * 1_000_000).round
# raise unless usec == i0
end
end
delta = ((s.total - f.total) / s.total) * 100.0
print "Performance increase: #{delta}\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment