1
  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​​ 中生成随机字符串?

4

5 回答 5

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)
于 2012-10-16T11:19:16.020 回答
2

不需要做36**1024 1000000 times

val=36**1024
1000000.times do
  rand(val).to_s(36)
end

这肯定会节省一些时间

于 2012-10-16T10:28:40.523 回答
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 秒

于 2012-10-16T10:28:48.480 回答
1

那么使用安全随机呢?

require 'securerandom'

start_time = Time.now
1000000 .times do
  SecureRandom.base64(1024)
end
end_time = Time.now
puts end_time - start_time
于 2012-10-16T10:29:42.290 回答
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 >   

=> 1.8 秒

所以简而言之Object.new.hash.to_s

于 2012-10-16T14:23:14.547 回答