C#测试程序运行时间的三种方法如下:
(1)Datetime
DateTime dtBegin = System.DateTime.Now;
... DateTime dtEnnd = System.DateTime.Now; TimeSpan dtTime = dtEnnd- dtBegin;
(2)Stopwatch
需要引用System.Diagnostics命名空间
Stopwatch sw = new Stopwatch(); sw.Start(); ... sw.Stop(); TimeSpan swTime = sw.Elapsed;
(3)Process.GetCurrentProcess()
TimeSpan gcpBegin = Process.GetCurrentProcess().TotalProcessorTime;
...
TimeSpan gcpTime = Process.GetCurrentProcess().TotalProcessorTime.Subtract(gcpBegin);
问题一:我的CPU数量是4,那计算CPU时间的话,需不需要除以4呢?
问题二:三种方法得到的时间是不同的,Datetime和Stopwatch得到的时间几乎一样,而Process.GetCurrentProcess()得到的时间远小于前两种,不是4倍关系,这又是为什么呢?
目前还没有找到答案,望高手指点一二。