Project

General

Profile

Feature #12484 » benchmark.rb

tad (Tadashi Saito), 06/12/2016 01:04 PM

 
require 'timeout'
require 'bigdecimal'

$VERBOSE = nil
M = 5
TIMEOUT = 1.0

def measure(proc)
(1..M).map do
n = 0
Timeout.timeout(TIMEOUT) do
loop do
proc.()
n += 1
end
end rescue nil
n
end.max
end

r = Rational(1, 3)
b1, b2 = (1 << 64) + 1, (1 << 64) + 3
r2 = Rational(b1)
r3 = -r
f, f2 = 10.0, -3.14
i = 10
bd = BigDecimal('0.1')
[
['Integer#gcd', ->{b1.gcd(b2)}],
['+', ->{r + r}],
['+ huge rational', ->{r + r2}],
['+ float', ->{r + f}],
['+ fixnum', ->{r + i}],
['+ bignum', ->{r + b1}],
['-', ->{r - r}],
['- huge rational', ->{r - r2}],
['- float', ->{r - f}],
['- fixnum', ->{r - i}],
['- bignum', ->{r - b1}],
['*', ->{r * r}],
['* huge rational', ->{r * r2}],
['* float', ->{r * f}],
['* fixnum', ->{r * i}],
['* bignum', ->{r * b1}],
['/', ->{r / r}],
['/ float', ->{r / f}],
['/ huge rational', ->{r / r2}],
['/ fixnum', ->{r / i}],
['/ bignum', ->{r / b1}],
['fdiv(0)', ->{r.fdiv(0)}],
['fdiv(1)', ->{r.fdiv(1)}],
['fdiv(2)', ->{r.fdiv(2)}],
['** fixnum', ->{r ** i}],
['** bignum', ->{r ** b1}],
['** float', ->{r ** f}],
['<=>', ->{r <=> r}],
['<=> float', ->{r <=> f}],
['<=> fixnum', ->{r <=> i}],
['ctor with bignum', ->{Rational(1, b1)}],
['ctor', ->{Rational(1, 3)}],
['==', ->{r == r2}],
['== bignum', ->{r2 == b1}],
['coerce(float)', ->{r.coerce(f)}],
['floor', ->{r.floor}],
['ceil', ->{r.ceil}],
['round', ->{r.round}],
['to_i', ->{r.to_i}],
['to_f', ->{r.to_f}],
['floor(n)', ->{r.floor(1)}],
['ceil(n)', ->{r.ceil(1)}],
['round(n)', ->{r.round(1)}],
['truncate(n)', ->{r.truncate(1)}],
['Numeric#numerator', ->{bd.numerator}],
['Numeric#denominator', ->{bd.denominator}],
['Numeric#quo(integer)', ->{2.quo(3)}],
['Float#numerator', ->{f.numerator}],
['Float#denominator', ->{f.denominator}],
['Float#to_r', ->{f.to_r}],
['Float#to_r (0.1)', ->{0.1.to_r}],
['1.0.rationalize', ->{1.0.rationalize}],
['-1.0.rationalize', ->{-1.0.rationalize}],
['10.0.rationalize(0.0)', ->{f.rationalize(0.0)}],
['0.0.rationalize', ->{0.0.rationalize}],
['10.0.rationalize', ->{f.rationalize}],
['-3.14.rationalize', ->{f2.rationalize}],
['Rational(\'1\')', ->{Rational('1')}],
['Rational(\'3.141592\')', ->{Rational('3.141592')}],
['Rational(\'-1e-10\')', ->{Rational('-1e-10')}],
['negative?', ->{r.negative?}],
['-rational.rationalize(some)', ->{r3.rationalize(r)}],
['Integer#lcm', ->{3.lcm(7)}],
['-@', ->{-r}],
].each do |label, proc|
puts label + "\t%d" % measure(proc)
STDOUT.flush
end
(4-4/7)