我分叉了几个流程,我需要每个流程来对随机选择的项目执行任务。我发现分叉的进程选择完全相同的随机数。我尝试生成种子并调用srand(),但并没有太大帮助。实际上,我阅读过的大多数文档都建议避免srand(),“除非您确切地知道自己在做什么”。
这是我的代码:
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use Time::HiRes qw(time);
use MongoDB;
#use Math::Random::Secure qw(rand);
my $num_clients = shift;
my $num_loops = 50_000_000;
sub test_forked_sub {
my $sum=0;
my $random_offset = rand(120);
printf "time: %10.4f - Random offset: %6.2f at pid: %s \n", time(), $random_offset, $$;
for (my $i=0; $i < $num_loops ; $i++) {
$sum += rand(120);
}
}
my $nub_processes = 0;
for (my $client_id =0; $client_id < $num_clients; $client_id++ ) {
if (my $pid …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法来生成良好的种子,以便在同时开始的过程中生成不同系列的随机数。我想避免使用数学库或加密库之一,因为我经常选择随机数,而且我的CPU资源非常有限。
我发现很少有树立种子的例子。我使用以下方法测试了它们:
这是我使用的perl代码。在每个测试中,我仅选择一种生成种子的方法:
#!/usr/bin/perl
#$seed=5432;
#$seed=(time ^ $$);
#$seed=($$ ^ unpack "%L*", `ps axww | gzip -f`);
$seed=(time ^ $$ ^ unpack "%L*", `ps axww | gzip -f`);
srand ($seed);
for ($i=0 ; $i< 100; $i++) {
printf ("%03d \n", rand (5000)+1000);
}
Run Code Online (Sandbox Code Playgroud)
我将程序运行了100次,并使用以下方法计算了未选择的值:
# run the program 100 times
for i in `seq 0 99`; do /tmp/rand_test.pl ; done > /tmp/list.txt
# test 1000 values (out of 5000). It should be good-enough representation.
for i in …Run Code Online (Sandbox Code Playgroud)