以微秒为单位的时间戳是否总是唯一的? [英] Is a timestamp in microseconds always unique?

查看:454
本文介绍了以微秒为单位的时间戳是否总是唯一的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

uniqid()基于当前时间戳(以微秒为单位)生成唯一ID.这真的是生成唯一ID的万无一失的方法吗?

uniqid() in PHP generates a unique ID based on the current timestamp in microseconds. Is that really a foolproof way to generate a unique ID?

即使假设有一个用户正在运行一个脚本,并且该脚本具有一个循环(以微秒为单位)生成时间戳,那么在理论上是否真的可以保证它是没有问题的?在实践中,可能性完全可以忽略不计吗?

Even assuming there's a single user running a single script with a loop generating a timestamp in microseconds, can there still really be a theoretical guarantee that it's unqiue? And in practice, is the likelihood completely negligible?

为清楚起见,请说您的循环不过是这样:

For clarity, say your loop is nothing more than this:

foreach($things as $thing){
    var_dump(microtime());
}

在理论上有没有可能不是唯一的机会?如果是这样,那么在实践中有多现实?

is there any theoretical chance it might not be unique and, if so, how realistic is it in practice?

推荐答案

基于微秒的ID仅保证在限制内唯一.在这方面,单台计算机上的单线程脚本可能很安全.但是,一旦您开始谈论并行执行,仅仅是在同一台计算机上的多个CPU上,或者特别是在多台计算机上,所有的赌注都将消失.

Microsecond based ids are only guaranteed to be unique within limits. A single threaded scripts on a single computer is probably pretty safe in this regard. However, as soon as you start talking about parallel execution, be that simply on multiple CPUs within the same machine or especially across multiple machines, all bets are off.

因此,这取决于您要使用此ID的用途.如果仅使用它来生成仅在同一脚本中使用的ID,则可能已经足够安全了.例如:

So it depends on what you want to use this id for. If you're just using it to generate an id which is used only within the same script, it's probably safe enough. For example:

<?php $randomId = uniqid(); ?>
<div id="<?php echo $randomId; ?>"></div>
<script>
    var div = document.getElementById('<?php echo $randomId; ?>');
    ...
</script>

在这种有限的使用范围内,您很可能不会遇到任何问题.

You very likely won't encounter any problems here with this limited use.

但是,如果您开始使用uniqid或与其他外部脚本共享的其他此类用法来生成文件名,则我不会依赖它.对于文件名,使用基于文件内容的哈希值可能是一个好主意.对于一般用途的分散的随机生成的ID, UUID 非常适合(因为它们是为这个目的).

However, if you start generating file names using uniqid or other such uses which are shared with other external scripts, I wouldn't rely on it. For filenames, using a hash based on the file contents may be a good idea. For general purpose decentralised randomly generated ids, UUIDs are a good fit (because they've been designed for this purpose).

这篇关于以微秒为单位的时间戳是否总是唯一的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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