我需要计算系统运行的持续时间。我的c#系统。我已经设置:
DateTime startRunningProg = Date.Time.Now("o");
经过几个过程。
我设置 :
DateTime endRunningProg = Date.Time.Now("o");
如何计算我的系统以毫秒或秒为单位运行的持续时间。
要准确测量经过的时间,请使用StopWatch类:
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
(endRunningProg - startRunningProg).TotalMilliseconds ;
但是@avs 是对的——使用 Stopwatch 类。请参阅此问题Stopwatch vs. using System.DateTime.Now 进行计时事件
使用秒表:
Stopwatch timer = Stopwatch.StartNew();
Thread.Sleep(1234);
timer.Stop();
TimeSpan timeSpan = timer.Elapsed;
Console.WriteLine("Total processing time... {0:00}:{1:00}:{2:00}.{3}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
// OUTPUT Total processing time... 00:00:01.243
使用日期时间:
DateTime start = DateTime.Now;
Thread.Sleep(1234);
DateTime end = DateTime.Now;
TimeSpan diff = (end - start);
Console.WriteLine("Total processing time... {0:00}:{1:00}:{2:00}.{3}", diff.Hours, diff.Minutes, diff.Seconds, diff.Milliseconds);
// OUTPUT Total processing time... 00:00:01.234
就像已经提到的那样,如果您尝试进行精确计时,那么您应该使用 StopWatch 类。
如果您真的想进行日期数学并找出两个日期之间的差异,我建议您查看Noda Time