我需要一种简单的方法(如果可能的话紧凑)来在计算时间的同时执行 C# 代码块。类似于此 C++ 代码的内容:
elapsed = time_call([&]
{
for_each (a.begin(), a.end(), [&](int n) {
results1.push_back(make_tuple(n, fibonacci(n)));
});
});
time_call 在哪里:
// Calls the provided work function and returns the number of milliseconds
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = GetTickCount();
f();
return GetTickCount() - begin;
}
我知道秒表的方式...还有更紧凑的吗?
最佳答案
TimeSpan TimeAction(Action blockingAction)
{
Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew();
blockingAction();
stopWatch.Stop();
return stopWatch.Elapsed;
}
用法:
var elapsed = TimeAction(() =>
{
//Code to time
});
根据您的示例代码(以及 GetTickCount
的用法),您可能希望返回 ElapsedTicks
而不是 Elapsed
。
关于c# - 如何轻松地为一段 C# 代码计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726386/