我需要找到一个瓶颈,并需要尽可能准确地测量时间。
下面的代码片段是衡量性能的最佳方法吗?
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);
当前回答
这是正确的方法:
using System;
using System.Diagnostics;
class Program
{
public static void Main()
{
Stopwatch stopWatch = Stopwatch.StartNew();
// some other code
stopWatch.Stop();
// this not correct to get full timer resolution
Console.WriteLine("{0} ms", stopWatch.ElapsedMilliseconds);
// Correct way to get accurate high precision timing
Console.WriteLine("{0} ms", stopWatch.Elapsed.TotalMilliseconds);
}
}
要了解更多信息,请使用秒表而不是DataTime来获得准确的性能计数器。
其他回答
将基准测试代码放入实用程序类/方法中是很有用的。StopWatch类不需要在错误时被丢弃或停止。最简单的为动作计时的代码是
public partial class With
{
public static long Benchmark(Action action)
{
var stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
}
示例调用代码
public void Execute(Action action)
{
var time = With.Benchmark(action);
log.DebugFormat(“Did action in {0} ms.”, time);
}
下面是扩展方法的版本
public static class Extensions
{
public static long Benchmark(this Action action)
{
return With.Benchmark(action);
}
}
以及示例调用代码
public void Execute(Action action)
{
var time = action.Benchmark()
log.DebugFormat(“Did action in {0} ms.”, time);
}
Visual Studio Team System有一些功能可以帮助解决这个问题。从本质上讲,您可以编写单元测试,并将它们混合在不同的场景中,作为压力或负载测试的一部分对您的软件运行。这可能有助于识别对应用程序性能影响最大的代码区域。
微软的模式和实践小组在Visual Studio团队系统性能测试指南中提供了一些指导。
我很少做这种性能检查(我倾向于认为“这个很慢,让它快一点”),所以我几乎总是这样做。
谷歌确实显示了许多用于性能检查的资源/文章。
许多人提到使用pinvoke来获取性能信息。我研究的很多材料都只提到了使用perfmon..
编辑:
看过秒表的对话..好了!我学到了一些东西:)
这篇文章看起来不错
使用System.Diagnostics.Stopwatch类。
Stopwatch sw = new Stopwatch();
sw.Start();
// Do some code.
sw.Stop();
// sw.ElapsedMilliseconds = the time your "do some code" took.
我刚刚在Vance Morrison的博客上找到了一篇关于他写的CodeTimer类的文章,这个类可以让使用StopWatch变得更容易,并在旁边做一些整洁的事情。