c# - 如何轻松地为一段 C# 代码计时?

标签 c# c++

我需要一种简单的方法(如果可能的话紧凑)来在计算时间的同时执行 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

关于c# - 如何轻松地为一段 C# 代码计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7726386/

相关文章:

java - 如何将字节数据从 C# 传递到 Java 中的 Servlet

c++ - spirit X3怎么加条件期望值

C++11 模板实例化错误

c++ - C 和 C++ 中关于 "^="运算符的区别

c++ - 如果不相等,比较和交换后返回对象?

c++ - 在 Windows 8 上显示虚拟键盘

c# - 如何在 Entity Framework Core 2.0 中映射值对象

c# - 根据窗口大小重组其单元格的网格?

c# - C# 中的 ComboBox 反射

c# - 两个不同的 "strings"是同一个对象实例吗?