How do i get from Stopwatch.GetTimestamp() to a DateTime?

坚强是说给别人听的谎言 提交于 2019-12-07 00:23:09

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1438652/how-do-i-get-from-stopwatch-gettimestamp-to-a-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!