Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to easily time a block of C# code?

Tags:

c++

c#

I need a simple way (and compact if possible) to execute a block of C# while counting time. Something similar to this C++ code:

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

where time_call is:

// 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;
}

I know the stopwatch way... anything more compact ?

like image 567
maborg Avatar asked Oct 11 '11 12:10

maborg


2 Answers

TimeSpan TimeAction(Action blockingAction)
{
    Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew();
    blockingAction();
    stopWatch.Stop();
    return stopWatch.Elapsed;
}

Usage:

var elapsed = TimeAction(() =>
    {
        //Code to time
    });

Based on your sample code (and usage of GetTickCount) you might want to return ElapsedTicks instead of Elapsed.

like image 55
George Duckett Avatar answered Oct 13 '22 18:10

George Duckett


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

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

   return elapsed;
}

How-to use:

var elapsed = TimeCall( () => { foreach( ... ) } );
like image 31
sll Avatar answered Oct 13 '22 18:10

sll