加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:57:23 所属栏目:百科 来源:网络整理
导读:我需要一个简单的方法(如果可能,紧凑)在计算时间时执行一个C#块.类似于这个C代码的东西: elapsed = time_call([] { for_each (a.begin(),a.end(),[](int n) { results1.push_back(make_tuple(n,fibonacci(n))); }); }); 其中time_call是: // Calls the pro
我需要一个简单的方法(如果可能,紧凑)在计算时间时执行一个C#块.类似于这个C代码的东西:
elapsed = time_call([&] 
   {
      for_each (a.begin(),a.end(),[&](int n) {
         results1.push_back(make_tuple(n,fibonacci(n)));
      });
   });

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

我知道秒表方式…什么更紧凑?

解决方法

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

用法:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读