C# 如何轻松地对C代码块计时?
我需要一种简单的方法(如果可能的话,可以压缩)在计算时间时执行一个C#块。类似于C++代码的类似内容:C# 如何轻松地对C代码块计时?,c#,c++,C#,C++,我需要一种简单的方法(如果可能的话,可以压缩)在计算时间时执行一个C#块。类似于C++代码的类似内容: elapsed = time_call([&] { for_each (a.begin(), a.end(), [&](int n) { results1.push_back(make_tuple(n, fibonacci(n))); }); }); 呼叫时间为: // Calls the provided wor
elapsed = time_call([&]
{
for_each (a.begin(), a.end(), [&](int n) {
results1.push_back(make_tuple(n, fibonacci(n)));
});
});
呼叫时间为:
// 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;
}
//调用提供的功函数并返回毫秒数
//调用该函数所需的时间。
模板
__int64时间调用(函数和函数)
{
__int64 begin=GetTickCount();
f();
返回GetTickCount()-begin;
}
我知道秒表的方法。。。还有更紧凑的吗?我不知道秒表的方式,但是C#也有lambdas,所以实现类似于time_call()的东西应该很容易 用法:
var elapsed = TimeAction(() =>
{
//Code to time
});
根据示例代码(以及
GetTickCount
的用法),您可能希望返回ElapsedTicks
,而不是appead
public double TimeCall(Action actionToExecute)
{
double elapsed = 0;
if (actionToExecute != null)
{
var stopwatch = Stopwatch.StartNew();
actionToExecute.Invoke();
elapsed = stopwatch.ElapsedMilliseconds;
}
return elapsed;
}
如何使用:
var elapsed = TimeCall( () => { foreach( ... ) } );
Stopwatch
有什么问题?Stopwatch方法需要大约3行代码,您希望它有多紧凑?前提是操作
明显是阻塞(即非异步)。默认情况下不“使用”System.Diagnostics。它应该是“System.Diagnostics.Stopwatch.StartNew()”,而不是“new Stopwatch.StartNew()”。我的意思是,StartNew()是一个静态方法,所以它前面不应该有一个“new”关键字。菲利普:哎呀,这是我创建一个新方法然后启动它时遗留下来的。
var elapsed = TimeCall( () => { foreach( ... ) } );