我想证明一个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#。
[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的很好的描述
如果你想在代码的许多地方检查guid的唯一性,你可以使用一个漂亮的小扩展方法。
internal static class GuidExt
{
public static bool IsUnique(this Guid guid)
{
while (guid != Guid.NewGuid())
{ }
return false;
}
}
要调用它,只需调用Guid。每当你生成一个新的guid…
Guid g = Guid.NewGuid();
if (!g.IsUnique())
{
throw new GuidIsNotUniqueException();
}
...见鬼,我甚至建议打电话两次,以确保它在第一轮就得到了正确的答案。
Go to the cryogenics lab in the New York City.
Freeze yourself for (roughly) 1990 years.
Get a job at Planet Express.
Buy a brand-new CPU. Build a computer, run the program, and place it in the safe place with an pseudo-perpetual motion machine like the doomsday machine.
Wait until the time machine is invented.
Jump to the future using the time machine. If you bought 1YHz 128bit CPU, go to 3,938,453,320 days 20 hours 15 minutes 38 seconds 463 ms 463 μs 374 ns 607 ps after when you started to run the program.
...?
PROFIT!!!
... 即使你的1YHz CPU是1GHz CPU的1,000,000,000,000,000倍(如果你更喜欢使用二进制前缀,则为1,125,899,906,842,624倍),也至少需要10,783,127年。
因此,与其等着计算结束,不如去喂那些因为其他n只鸽子夺走了它们的家而失去家园的鸽子。:(
或者,你可以等到128位量子计算机被发明出来。然后,您可以通过在合理的时间内(可能)使用您的程序来证明GUID不是唯一的。