Reputation: 8973
check the code
StringBuilder s = new StringBuilder();
for (var i = 0; i < 100; i++)
{
TimeSpan t = (DateTime.UtcNow - new DateTime(2010, 1, 1));
ulong timestamp = (ulong)(t.TotalMilliseconds * 100000000);
s.Append("<li>" + timestamp.ToString());
}
You will get same result 100 times, it means the DateTime.UtcNow never changes even I multiply milliseconds by 100000000 times.
Is here anyone know how to get fresh DateTime.UtcNow each time?
Upvotes: 0
Views: 553
Reputation: 51
The best way is to use System.Diagnostics.Stopwatch
class to measure the time span with high resolution. On most computers the default clock interval is 15.625 ms, which means within a clock interval the difference of two timestamps retrieved using DateTime.UtcNow
will be 0. Stopwatch
uses perf counter whenever available (i.e. on most PCs) and the resolution is usually less than 1 us. See Time Span Measurement in Managed Code for more details.
Upvotes: 0
Reputation: 10790
I just put your snippet in LinqPad and added a t.TotalMilliseconds.Dump()
right before the end of the for loop, here are the first few results:
61068982141.4911
61068982143.9916
61068982143.9916
61068982144.4917
61068982144.4917
61068982144.4917
61068982144.4917
61068982144.9918
61068982144.9918
61068982144.9918
61068982144.9918
61068982145.4919
61068982145.4919
61068982145.4919
61068982145.4919
61068982145.992
61068982145.992
61068982145.992
61068982145.992
The loop is executing rather fast, you're seeing fractional ms there after the decimal.
Upvotes: 0