In [1]:
require 'matplotlib/iruby'
Matplotlib::IRuby.activate

require 'pycall/import'
include PyCall::Import

pyimport :pandas, as: :pd
pyimport :seaborn, as: :sns


Out[1]:
:sns

In [2]:
require 'benchmark'


Out[2]:
true

In [3]:
n = 100_000
trials = 100
array = Array.new(n) { rand }
enum = array.each
method = []
runtime = []


Out[3]:
[]

In [4]:
# Array#sum
trials.times do
  method << 'array.sum'
  runtime << Benchmark.realtime { array.sum }
end


Out[4]:
100

In [5]:
# Array#sum
trials.times do
  method << 'enum.sum'
  runtime << Benchmark.realtime { enum.sum }
end


Out[5]:
100

In [6]:
# Array#inject
trials.times do
  method << 'array.inject'
  runtime << Benchmark.realtime { array.inject :+ }
end


Out[6]:
100

In [7]:
# Enumerable#inject
trials.times do
  method << 'enum.inject'
  runtime << Benchmark.realtime { enum.inject :+ }
end


Out[7]:
100

In [8]:
# while
def while_sum(array)
  sum, i, cnt = 0, 0, array.length
  while i < cnt
    sum += array[i]
    i += 1
  end
  sum
end

trials.times do
  method << 'while'
  runtime << Benchmark.realtime { while_sum(array) }
end


Out[8]:
100

In [9]:
df = pd.DataFrame.new(data: {method: method, runtime: runtime})
df.groupby('method').describe()


Out[9]:
runtime
count mean std min 25% 50% 75% max
method
array.inject 100.0 0.013103 0.001518 0.012029 0.012350 0.012590 0.013337 0.022215
array.sum 100.0 0.001882 0.000372 0.001498 0.001587 0.001804 0.002008 0.003009
enum.inject 100.0 0.023528 0.002267 0.021078 0.021782 0.023041 0.024574 0.033859
enum.sum 100.0 0.010069 0.001304 0.009078 0.009221 0.009463 0.010708 0.018378
while 100.0 0.011932 0.001089 0.011079 0.011357 0.011491 0.012085 0.018309

In [10]:
sns.barplot(x: 'method', y: 'runtime', data: df, errwidth: 2.5, capsize: 0.04)
plt = Matplotlib::Pyplot
plt.title("Array and Enumerable summation benchmark (#{trials} trials)")
plt.xlabel("Summation method")
plt.ylabel("Average runtime [sec]")


Out[10]:
Out[10]:
#<Object:0x007fd93f020088 @__pyptr__=#<PyCall::PyPtr:0x007fd93f020010 type=Text addr=0x000001176abe10>>

In [ ]: