c# stopwatch.elapsed 值不准确
c# stopwatch.elapsed values innaccurate
我想计算我正在编写的程序的总时间运行。
目前代码看起来与此类似(sw 是程序 class 的成员):
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
我想计算我正在编写的程序的总时间运行。
目前代码看起来与此类似(sw 是程序 class 的成员):
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