start_time = Time.now
1000000.times do
rand(36**1024).to_s(36)
end
end_time = Time.now
puts end_time - start_time
235秒。
有没有更快的方法在ruby中生成随机字符串?
答案 0 :(得分:3)
如果您的目标系统有 / dev / urandom ,您可以从中读取随机字节。它应该更快。这是带基准的代码。一些Ruby库使用这种方法生成随机事物。
Benchmark.bm do|b|
b.report("Ruby #rand ") do
100000.times do
big_key = rand(36**1024).to_s(36)
end
end
b.report("/dev/urandom") do
File.open("/dev/urandom",File::RDONLY || File::NONBLOCK || File::NOCTTY) do |f|
100000.times do
big_key = f.readpartial(512).unpack("H*")[0]
end
end
end
end
在这里你可以看到100000的基准测试结果,1024个字符长的随机字符串......
user system total real
Ruby #rand 31.750000 0.080000 31.830000 ( 32.909136)
/dev/urandom 0.810000 5.870000 6.680000 ( 6.974276)
答案 1 :(得分:2)
不需要36**1024
1000000 times
val=36**1024
1000000.times do
rand(val).to_s(36)
end
这肯定会节省一些时间
答案 2 :(得分:1)
您可以随机播放字符串以获取随机字符串
array = rand(36**1024).to_s(36).split(//)
start_time = Time.now
1000000.times do
array.shuffle.join
end
end_time = Time.now
puts end_time - start_time
#=> 126秒
答案 3 :(得分:1)
使用securerandom怎么样?
require 'securerandom'
start_time = Time.now
1000000 .times do
SecureRandom.base64(1024)
end
end_time = Time.now
puts end_time - start_time
答案 4 :(得分:0)
1.9.3p194 :113 >
1.9.3p194 :114 > start_time = Time.now
=> 2012-10-16 19:51:45 +0530
1.9.3p194 :115 > 1000000.times do
1.9.3p194 :116 > (Object.new.hash.to_s << Object.new.hash.to_s)[0..35]
1.9.3p194 :117?> end
=> 1000000
1.9.3p194 :118 > end_time = Time.now
=> 2012-10-16 19:51:46 +0530
1.9.3p194 :119 > puts end_time - start_time
1.8252512
=> nil
1.9.3p194 :120 >
=&GT; 1.8秒
简而言之Object.new.hash.to_s