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 ?
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
.
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( ... ) } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With