我想证明一个GUID在一个简单的测试程序中不是唯一的。 我原以为下面的代码会运行几个小时,但它不起作用。我该怎么做呢?

BigInteger begin = new BigInteger((long)0);
BigInteger end = new BigInteger("340282366920938463463374607431768211456",10);  //2^128
for(begin; begin<end; begin++)
  Console.WriteLine(System.Guid.NewGuid().ToString());

我用的是c#。


当前回答

对我来说. .单个核心生成UUIDv1所需的时间保证了它是唯一的。即使在多核情况下,如果UUID生成器一次只允许为特定资源生成一个UUID(请记住,多个资源可以完全利用相同的UUID,但不太可能,因为资源本身就是地址的一部分),那么您将拥有足够多的UUID,直到时间戳耗尽为止。在这一点上,我真的怀疑你会在乎。

其他回答

[Update:] As the comments below point out, newer MS GUIDs are V4 and do not use the MAC address as part of the GUID generation (I haven't seen any indication of a V5 implementation from MS though, so if anyone has a link confirming that let me know). WIth V4 though, time is still a factor though, and the odds against duplication of GUIDs remains so small as to be irrelevant for any practical usage. You certainly would not be likely to ever generate a duplicate GUID from just a single system test such as the OP was trying to do.

大多数答案都忽略了微软GUID实现的一个关键点。GUID的第一部分基于时间戳,另一部分基于网卡的MAC地址(如果没有安装网卡,则为随机数)。

如果我理解正确,这意味着复制GUID的唯一可靠方法是在多台机器上同时运行GUID生成,其中MAC地址是相同的,并且两个系统上的时钟在生成发生时处于相同的确切时间(时间戳是基于毫秒的,如果我理解正确的话)....即使如此,数字中还有很多其他的位是随机的,所以几率仍然很小。

对于所有实际目的,guid都是惟一的。

在“旧的新事物”博客上有一个关于MS GUID的很好的描述

数到2^128,雄心勃勃。

让我们想象一下,每台机器每秒可以计算2^32个id——不是那么雄心勃勃,因为它甚至不到每秒43亿个。让我们用2^32台机器来完成这个任务。此外,让2^32个文明各自投入相同的资源来完成任务。

到目前为止,我们每秒可以计数2^96个id,这意味着我们将计数2^32秒(136年多一点)。

现在,我们所需要的是获得4294967296个文明,每个文明都有4294967296台机器,每台机器每秒能计算4294967296个id,在未来136年左右的时间里,纯粹是为了这项任务——我建议我们现在就开始这项基本任务;-)

Well if the running time of 83 billion years does not scare you, think that you will also need to store the generated GUIDs somewhere to check if you have a duplicate; storing 2^128 16-byte numbers would only require you to allocate 4951760157141521099596496896 terabytes of RAM upfront, so imagining you have a computer which could fit all that and that you somehow find a place to buy terabyte DIMMs at 10 grams each, combined they will weigh more than 8 Earth masses, so you can seriously shift it off the current orbit, before you even press "Run". Think twice!

由于部分Guid生成是基于当前机器的时间,我的理论是获得一个副本Guid:

重新安装Windows 创建一个启动脚本,在Windows启动时将时间重置为2010-01-01 12:00:00。 就在启动脚本之后,它触发应用程序生成一个Guid。 克隆此Windows安装,以便排除后续启动过程中可能出现的任何细微差异。 用此映像重新映像硬盘驱动器,并启动几次机器。

就我个人而言,我认为“大爆炸”是由两个guid相撞引起的。