8

Duplicate of: How to get timestamp of tick precision in .NET / C#?
How do i get from Stopwatch.GetTimestamp() to a DateTime

Assume Stopwatch.IsHighResolution is true

Community
  • 1
  • 1
Simon
  • 33,714
  • 21
  • 133
  • 202

2 Answers2

8

If it's a high resolution counter, there's no guarantee that the value has any correlation with the real time - for example, it may well be "ticks since the computer booted." For a non-high resolution timer, you could use new DateTime(Stopwatch.GetTimestamp()) but that won't necessarily give a useful value for a high resolution timer. (It certainly doesn't on my box.)

What are you trying to use this for? The idea of Stopwatch is to measure intervals of time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Wanted to ask why "no correlation"? OS ticks are constant so a 100 ms should be very similar to 100 ms on any clock (in terms of interval). The only way they should differ is a shift between the real time and the OS tick counter initialization, correct? After the Os ticks counter is initialized the interval length should be the same as a for "any" accurate clock? – Mindaugas Bernatavičius Jul 27 '17 at 08:59
  • 5
    @Mindaugas: The system clock could have changed due to a time zone change, manual time correction or automatic correction e.g. via NTP. The point is that if you want to measure elapsed time, you use a Stopwatch, but that *won't* give you a DateTime because it only measures elapsed time. – Jon Skeet Jul 27 '17 at 11:14
  • Thanks a lot! I was thinking about a shorter time range, but thanks for giving me some more understanding. – Mindaugas Bernatavičius Jul 27 '17 at 11:31
0

Keep in mind that if you're trying to track elapsed time you should use:

Stopwatch sw = Stopwatch.StartNew();
//do stuff
sw.Elapsed; //or
sw.ElapsedMilliseconds;

This accurately converts ticks to real time. Converting the ticks to a DateTime, and then comparing the DateTimes would also work, but the above is simpler.

Some (including myself) have erroneously used code like this, and got bad times from it:

startTime = Stopwatch.GetTimestamp();

totalTime = (Stopwatch.GetTimestamp() - startTime) / 10000; 
//it was assumed 10,000 ticks was a millisecond, incorrectly
Dmitri R117
  • 2,502
  • 23
  • 20
  • 11
    Stopwatch.Frequency, which is the amount of ticks pr. sec, can be used to correct your last example: elapsedMs = (Stopwatch.GetTimestamp() - startTime) / (Stopwatch.Frequency / 1000); – Jens Nov 11 '16 at 10:19