如何轻松地计算一个C#代码块? [英] How to easily time a block of C# code?

查看:130
本文介绍了如何轻松地计算一个C#代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个简单的方法(如果可能,紧凑)执行一个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)));
      });
   });   

其中time_call是:

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

用法:

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






根据您的示例代码code> GetTickCount ),您可能希望返回 ElapsedTicks 而不是 Elapsed


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

这篇关于如何轻松地计算一个C#代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆