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'
# 100種類の乱数の配列のデータを取る
n = 100
# 配列の要素の最大値が100...100000まで比較
[100, 1000, 10000, 100000, 1000000, 10000000].each do |max|
# 毎回異なる要素数100000個の乱数の配列に対して100回操作
sources = n.times.map do
100000.times.map do
rand(max)
end
end
p "max_value: #domaxend"
Benchmark.bm(5) do |x|
x.report('uniq') do
sources.each do |source|
source.uniq
end
end
x.report('set') do
sources.each do |source|
Set.new(source.dup)
end
end
x.report('hash') do
sources.each do |source|
source.dup.each_with_object(Hash.new) do|i, h| h[i] end.keys end
end
#破壊的な操作なので最後
x.report('uniq!') do
sources.each do |source|
source.uniq!
end
end
end
end
"max_value: 100"
user system total real
uniq 0.960000 0.000000 0.960000 ( 0.970205)
set 2.760000 0.010000 2.770000 ( 2.788782)
hash 1.580000 0.000000 1.580000 ( 1.586609)
uniq! 1.090000 0.020000 1.110000 ( 1.120790)
"max_value: 1000"
user system total real
uniq 1.170000 0.010000 1.180000 ( 1.186608)
set 3.020000 0.010000 3.030000 ( 3.046173)
hash 1.560000 0.000000 1.560000 ( 1.571826)
uniq! 1.140000 0.020000 1.160000 ( 1.165698)
"max_value: 10000"
user system total real
uniq 1.580000 0.000000 1.580000 ( 1.591290)
set 3.090000 0.030000 3.120000 ( 3.128032)
hash 1.360000 0.000000 1.360000 ( 1.363069)
uniq! 1.660000 0.020000 1.680000 ( 1.693592)
"max_value: 100000"
user system total real
uniq 4.510000 0.060000 4.570000 ( 4.581352)
set 5.580000 0.170000 5.750000 ( 5.769500)
hash 1.320000 0.000000 1.320000 ( 1.334091)
uniq! 4.610000 0.060000 4.670000 ( 4.692547)
"max_value: 1000000"
user system total real
uniq 6.220000 0.090000 6.310000 ( 6.320836)
set 7.870000 0.270000 8.140000 ( 8.226232)
hash 1.360000 0.010000 1.370000 ( 1.364586)
uniq! 6.170000 0.090000 6.260000 ( 6.291180)
"max_value: 10000000"
user system total real
uniq 6.260000 0.100000 6.360000 ( 6.378876)
set 7.530000 0.280000 7.810000 ( 7.838983)
hash 1.410000 0.000000 1.410000 ( 1.414521)
uniq! 6.500000 0.110000 6.610000 ( 6.633919)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment