如何轻松计时一块C#代码?

mab*_*org 9 c# c++

我需要一种简单的方法(如果可能的话,紧凑)在计算时间时执行一个C#块.与此C++代码类似的东西:

elapsed = time_call([&] 
   {
      for_each (a.begin(), a.end(), [&](int n) {
         results1.push_back(make_tuple(n, fibonacci(n)));
      });
   });   
Run Code Online (Sandbox Code Playgroud)

其中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;
}
Run Code Online (Sandbox Code Playgroud)

我知道秒表的方式......更紧凑吗?

Geo*_*ett 14

TimeSpan TimeAction(Action blockingAction)
{
    Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew();
    blockingAction();
    stopWatch.Stop();
    return stopWatch.Elapsed;
}
Run Code Online (Sandbox Code Playgroud)

用法:

var elapsed = TimeAction(() =>
    {
        //Code to time
    });
Run Code Online (Sandbox Code Playgroud)

根据您的示例代码(和用法GetTickCount),您可能希望返回ElapsedTicks而不是Elapsed.


sll*_*sll 6

public double TimeCall(Action actionToExecute)
{
   double elapsed = 0;

   if (actionToExecute != null)
   {
      var stopwatch = Stopwatch.StartNew();
      actionToExecute.Invoke();
      elapsed = stopwatch.ElapsedMilliseconds;
   }

   return elapsed;
}
Run Code Online (Sandbox Code Playgroud)

如何使用:

var elapsed = TimeCall( () => { foreach( ... ) } );
Run Code Online (Sandbox Code Playgroud)