简单的时间分析 - 奇怪的时间

Gac*_*cek 2 c#

我正在尝试分析我的代码以检查执行代码的某些部分需要多长时间.

我把代码中最费时的部分包装成了这样的东西:

DateTime start = DateTime.Now;
...
... // Here comes the time-consuming part
... 
Console.WriteLine((DateTime.Now - start).Miliseconds);
Run Code Online (Sandbox Code Playgroud)

程序正在执行这部分代码几秒钟(大约20秒),但在控制台中我得到的结果约为800毫秒.为什么会这样?我究竟做错了什么?

Ree*_*sey 11

尝试使用秒表课程.它的目的是为了这个目的.

Stopwatch sw = Stopwatch.StartNew();
// ...
// Here comes the time-consuming part
// ...
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)


Zac*_*son 8

你真的想要TotalMilliseconds属性吗? Milliseconds返回时间跨度的毫秒分量,而不是实际的时间长度(以毫秒为单位).

也就是说,您可能想要使用秒表(正如其他人所说),因为它会更准确.