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
  • Save ainame/2647349 to your computer and use it in GitHub Desktop.
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: #{max}"
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)
end
end
x.report('hash') do
sources.each do |source|
source.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: 100"
user system total real
uniq 0.910000 0.010000 0.920000 ( 0.918938)
set 2.410000 0.000000 2.410000 ( 2.419544)
hash 1.350000 0.000000 1.350000 ( 1.357918)
uniq! 0.910000 0.010000 0.920000 ( 0.919179)
"max: 1000"
user system total real
uniq 1.010000 0.000000 1.010000 ( 1.007825)
set 2.460000 0.010000 2.470000 ( 2.486916)
hash 1.390000 0.010000 1.400000 ( 1.391193)
uniq! 0.980000 0.000000 0.980000 ( 0.987927)
"max: 10000"
user system total real
uniq 1.620000 0.000000 1.620000 ( 1.630699)
set 3.330000 0.040000 3.370000 ( 3.383102)
hash 1.470000 0.000000 1.470000 ( 1.473038)
uniq! 1.650000 0.010000 1.660000 ( 1.669997)
"max: 100000"
user system total real
uniq 4.650000 0.060000 4.710000 ( 4.723563)
set 5.750000 0.170000 5.920000 ( 5.954741)
hash 1.390000 0.000000 1.390000 ( 1.401017)
uniq! 4.560000 0.070000 4.630000 ( 4.646408)
"max: 1000000"
user system total real
uniq 6.190000 0.090000 6.280000 ( 6.309521)
set 7.580000 0.270000 7.850000 ( 7.880618)
hash 1.430000 0.000000 1.430000 ( 1.443003)
uniq! 6.260000 0.110000 6.370000 ( 6.393830)
"max: 10000000"
user system total real
uniq 6.510000 0.090000 6.600000 ( 6.632788)
set 8.040000 0.310000 8.350000 ( 8.379355)
hash 1.350000 0.000000 1.350000 ( 1.359664)
uniq! 6.660000 0.120000 6.780000 ( 6.800269)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment