我需要找到一个瓶颈,并需要尽可能准确地测量时间。
下面的代码片段是衡量性能的最佳方法吗?
DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
我需要找到一个瓶颈,并需要尽可能准确地测量时间。
下面的代码片段是衡量性能的最佳方法吗?
DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
当前回答
Visual Studio Team System有一些功能可以帮助解决这个问题。从本质上讲,您可以编写单元测试,并将它们混合在不同的场景中,作为压力或负载测试的一部分对您的软件运行。这可能有助于识别对应用程序性能影响最大的代码区域。
微软的模式和实践小组在Visual Studio团队系统性能测试指南中提供了一些指导。
其他回答
我在程序中使用的方式是使用StopWatch类,如下所示。
Stopwatch sw = new Stopwatch();
sw.Start();
// Critical lines of code
long elapsedMs = sw.Elapsed.TotalMilliseconds;
因为我不太关心精度,所以我最终比较了它们。我正在捕获网络上的大量数据包,我想在我收到每个数据包时放置时间。下面是测试500万次迭代的代码
int iterations = 5000000;
// Test using datetime.now
{
var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (date == DateTime.Now)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
// Test using datetime.utcnow
{
var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (date == DateTime.UtcNow)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
// Test using stopwatch
{
Stopwatch sw = new Stopwatch();
sw.Start();
var now = DateTime.UtcNow;
for (int i = 0; i < iterations; i++)
{
if (sw.ElapsedTicks == DateTime.Now.Ticks)
Console.WriteLine("it is!");
}
Console.WriteLine($"Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds");
}
输出结果为:
Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds
Done executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds
Done executing 5000000 iterations using stopwatch. It took 0.9625021 seconds
总之,DateTime。如果您不太关心精度,UtcNow是最快的。这也支持了这个问题的答案https://stackoverflow.com/a/6986472/637142。
我很少做这种性能检查(我倾向于认为“这个很慢,让它快一点”),所以我几乎总是这样做。
谷歌确实显示了许多用于性能检查的资源/文章。
许多人提到使用pinvoke来获取性能信息。我研究的很多材料都只提到了使用perfmon..
编辑:
看过秒表的对话..好了!我学到了一些东西:)
这篇文章看起来不错
这些都是衡量时间的好方法,但这只是发现瓶颈的一种非常间接的方法。
在线程中找到瓶颈的最直接方法是让它运行,当它正在做任何让您等待的事情时,使用暂停或中断键停止它。这样做几次。如果你的瓶颈占用了X%的时间,那么X%就是你在每次快照中捕捉到它的概率。
这里有一个更完整的解释,它是如何以及为什么工作的
使用System.Diagnostics.Stopwatch类。
Stopwatch sw = new Stopwatch();
sw.Start();
// Do some code.
sw.Stop();
// sw.ElapsedMilliseconds = the time your "do some code" took.