Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.