PageRenderTime 15ms CodeModel.GetById 1ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/test-suite/ruby/ruby_li_std_speed_runme.rb

#
Ruby | 82 lines | 63 code | 11 blank | 8 comment | 8 complexity | 723cb3503ec43dbe23cd2c29f9c63001 MD5 | raw file
 1#!/usr/bin/env ruby
 2#
 3# This is a simple speed benchmark suite for std containers,
 4# to verify their O(n) performance.
 5# It is not part of the standard tests.
 6
 7
 8require 'benchmark'
 9require 'mathn'
10require 'ruby_li_std_speed'
11include Ruby_li_std_speed
12
13
14def benchmark(f, phigh, sequences)
15  puts f
16  print '%10s' % 'n'
17  maxlen = sequences.max { |a,b| a.to_s.size <=> b.to_s.size }
18  maxlen = maxlen.to_s.size - 12
19  sequences.each { |s| print "%#{maxlen}s" % "#{s.to_s.sub(/.*::/,'')}" }
20  puts
21  o_perf = Array.new(sequences.size, 0)
22  last_t = Array.new(sequences.size, nil)
23  1.upto(phigh) do |p|
24    n = 2**(p-1)
25    print "%10d" % n
26    sequences.each_with_index do |s, i|
27      cont = s.new((0..n).to_a)
28      Benchmark.benchmark('',0,"%#{maxlen-2}.6r") { |x|
29        t = x.report { f.call(cont) }
30        o_perf[i] += last_t[i] ? (t.real / last_t[i]) : t.real
31        last_t[i] = t.real
32      }
33    end
34    puts
35  end
36
37  print "  avg. O(n)"
38  base = 1.0 / Math.log(2.0)
39  sequences.each_with_index do |s, i|
40    o_perf[i] /= phigh
41    # o_perf[i] = 1 if o_perf[i] < 1
42    o_perf[i]  = Math.log(o_perf[i]) * base
43    print "%#{maxlen-1}.2f " % o_perf[i]
44  end
45  puts
46end
47
48def iterate(cont)
49   it = cont.begin
50   last = cont.end
51   while it != last 
52     it.next
53   end
54end
55
56
57def erase(cont)
58   it = cont.end
59   # can't reuse begin since it might get invalidated
60   while it != cont.begin
61     it.previous
62     # set returns None, so need to reobtain end
63     it = cont.erase(it) || cont.end
64   end
65end
66
67def insert(cont)
68  size = cont.size
69  size.upto((size<<1) - 1) { |x| cont.push(x) }
70end
71
72if $0 == __FILE__
73  GC.disable
74  sequences = [RbVector,RbDeque,RbSet,RbList,
75               RbFloatVector,RbFloatDeque,RbFloatSet,RbFloatList]
76  n = 17
77  for f,phigh in [[method(:iterate),n], [method(:insert),n],
78                  [method(:erase),n-4]]
79    benchmark(f, phigh, sequences)
80  end
81end
82