Skip to content

Instantly share code, notes, and snippets.

@NewAlexandria
Created January 13, 2012 17:03
Show Gist options
  • Save NewAlexandria/1607539 to your computer and use it in GitHub Desktop.
Save NewAlexandria/1607539 to your computer and use it in GitHub Desktop.
Ruby comparison of BigDecimal vs. Float
# I've compiled this in order to test the speed on using a BidDecimal, which some in the community assert is slower than using a float.
# So far, it looks like BigDecimal is faster, and I've created this file to solicit feedback. Cheers.
run_size = 10000
p_fin = []
p_fin << "Each run #{run_size}"
t1 = Time.now
run_size.times do
r = BigDecimal.new
r = rand
s = BigDecimal.new
s = rand
t = r/s
end
p_fin << [Time.new - t1, "BigDecimal = rand"]
t1 = Time.now
run_size.times do
r = BigDecimal.new( rand.to_s )
s = BigDecimal.new( rand.to_s )
t = r/s
end
p_fin << [Time.new - t1, "BigDecimal(rand.to_s)"]
t1 = Time.now
run_size.times do
r = Float.new
r = rand.round(14)
s = Float.new
s = rand.round(14)
t = r/s
end
p_fin << [Time.new - t1, "float.round."]
t1 = Time.now
run_size.times do
r = Float.new
r = rand
s = Float.new
s = rand
t = r/s
end
p_fin << [Time.new - t1, "float."]
pp p_fin
@nertzy
Copy link

nertzy commented Jan 16, 2012

Careful, every time you do this you're not doing anything different:

r = Float.new
r = rand

and

r = BigDecimal.new
r = rand

In both cases, the object created in the first line is thrown away and r is reassigned to the return value of Kernel#rand, which is a Float

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment