首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c# stopwatch.elapsed值不准确

c# stopwatch.elapsed值不准确
EN

Stack Overflow用户
提问于 2015-01-19 18:14:24
回答 1查看 174关注 0票数 1

我想对我正在进行的一个项目的总运行时间进行计时。

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

代码语言:javascript
复制
 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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-19 20:41:45

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28031045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档