繁体   English   中英

c#stopwatch.elapsed值不正确

[英]c# stopwatch.elapsed values innaccurate

我想计时我正在制作的节目的总运行时间。

当前,代码看起来与此类似(sw是程序类的成员):

 void Main(string[] args)
 {
     sw.Start();
     //Code here starts a thread
     //Code here joins the thread
     //Code operates on results of threaded operation
     sw.Stop();
     Console.WrtieLine("Operation took {0}", sw.Elapsed.ToString());
 }

我认为此问题是由线程控制程序执行引起的,但这是最耗时的操作,我应该避免更改代码,因为其他项目也依赖它。

作为参考,简单的观察表明该代码需要花费近半个小时来运行,但是根据秒表的经过时间仅为23秒左右。 确切的输出Operation took 00:00:23.1064841

在这种情况下,最好的解决方案是使用Environment.TickCount因为它可以测量系统启动后的毫秒数,并且不像Stopwatch那样依赖处理器核心。

int StartTime = Environment.TickCount;
//Your Code to measure here
int EndTime = Environment.TickCount;
int runningTime = EndTime - StartTIme; //running time in milliseconds
// code to do whatever you want with runningTime

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM