Domanda

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?

È stato utile?

Soluzione

In such a tight loop chances are indeed good that you will be getting the same time.

Each tick in the Ticks property represent a 100 nano-second slice. Your code would iterate faster than that.

Altri suggerimenti

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.

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top