Skip to content

Instantly share code, notes, and snippets.

@ainame
Forked from takai/1. uniq_bench.rb
Created May 9, 2012 17:58
Show Gist options
  • Select an option

  • Save ainame/2647349 to your computer and use it in GitHub Desktop.

Select an option

Save ainame/2647349 to your computer and use it in GitHub Desktop.
正しそうな結果が得られるように変更しました
# -*- coding: utf-8 -*-
require 'benchmark'
require 'set'
# 1回の配列の生成に対して100回の平均をとる
n = 100
# 配列の要素の最大値が100...100000まで比較
[100, 1000, 10000, 100000, 1000000, 10000000].each do |max|
# 5回のベンチの平均
Benchmark.bm(5) do |x|
# 要素数100000個の乱数の配列に対して操作
source = 100000.times.map { rand(max) }
p "max_value: #{max}"
x.report('uniq') do n.times { source.dup.uniq.size } end
x.report('uniq!') do n.times { source.dup.uniq! } end
x.report('set') do n.times { Set.new(source.dup) } end
x.report('hash') do n.times { source.dup.each_with_object(Hash.new) {|i, h| h[i] }.keys } end
end
end
user system total real
"max_value: 100"
uniq 0.950000 0.000000 0.950000 ( 0.950976)
uniq! 0.890000 0.010000 0.900000 ( 0.902435)
set 2.380000 0.000000 2.380000 ( 2.386007)
hash 1.350000 0.000000 1.350000 ( 1.355174)
user system total real
"max_value: 1000"
uniq 1.010000 0.010000 1.020000 ( 1.020505)
uniq! 1.060000 0.000000 1.060000 ( 1.064673)
set 2.630000 0.010000 2.640000 ( 2.653748)
hash 1.440000 0.000000 1.440000 ( 1.441658)
user system total real
"max_value: 10000"
uniq 1.710000 0.000000 1.710000 ( 1.724164)
uniq! 1.680000 0.000000 1.680000 ( 1.683601)
set 3.270000 0.020000 3.290000 ( 3.289946)
hash 1.470000 0.000000 1.470000 ( 1.470825)
user system total real
"max_value: 100000"
uniq 4.500000 0.080000 4.580000 ( 4.581424)
uniq! 4.690000 0.080000 4.770000 ( 4.781564)
set 5.630000 0.100000 5.730000 ( 5.735537)
hash 1.490000 0.010000 1.500000 ( 1.491445)
user system total real
"max_value: 10000000"
uniq 6.980000 0.130000 7.110000 ( 7.143206)
uniq! 7.040000 0.130000 7.170000 ( 7.198300)
set 8.300000 0.180000 8.480000 ( 8.512272)
hash 1.500000 0.000000 1.500000 ( 1.505083)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment