rand()在php中是时间相关的吗? [英] Is rand() time-dependent in php?

查看:85
本文介绍了rand()在php中是时间相关的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们解释一下我的意思.

Let we explain what I mean.

前一段时间,在用C#编写程序时,我犯了以下错误:

Some time ago, while writing a program in c#, I've made following mistake:

int Randomize()
{
    Random r=new Random();
    return  r.Next(0,10);
}

在c#中,这是一个错误,因为连续调用多次,此函数将返回相同的值.这是因为Random构造函数使用时间种子,并且两次调用之间的时间差太小(花了我一个小时才找到一个:)).

in c#, this is a mistake, because, called several times in a row, this function will return the same value. This is because Random constructor uses time seed, and the time difference between calls was too low (took me an hour to find that one :) ).

现在我正在php中使用rand(...),即使两个脚本同时执行,我也需要输出始终是不同的.

Now I'm using rand(...) in php, and I need for the output to always be different, even if 2 scripts are executed at the same time.

我是否需要做一些事情才能获得此结果,或者它是否设计为以这种方式工作?

Do I have to do something to get this result, or is it designed to work this way?

推荐答案

rand()mt_rand()调用srand()mt_srand()来产生总是随机的结果. 但是,这是php.net上的一个有趣的帖子:

the rand() and also mt_rand() calls srand() and mt_srand() to produce always random results. But here's an interesting post on php.net:

请注意,自动播种似乎是通过当前 秒数,这意味着您可以在几秒钟内获得相同的结果 在快速的服务器上运行.要么自己调用srand() 经常更改种子或使用mt_rand()似乎并不 遭受问题困扰.

Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server. Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.

因此,只需更频繁地拨打srandmt_rand.

So, just call srand more frequently or mt_rand.

这篇关于rand()在php中是时间相关的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆