如何记录C 重复迭代函数的总时间

How To record total timing for C++ repetive Iterative function?

本文关键字:迭代 函数 时间 何记录 记录      更新时间:2023-10-16

我有此功能原型代码用于迭代计算我如何包括一个计时器来产生用于循环100次功能的总时间?

for(未签名的长i = number; i> = 1; i-)结果 *= i;

我的C 知识几乎是基本的,因此不确定此处是否正确提及"循环"。但是,我被暗示要使用。

pls建议

谢谢

这是某些时序逻辑的正确C 11版:

using namespace std;
using namespace chrono;
auto start_time = system_clock::now();
// your loop goes here:
for (unsigned long i=number; i>=1; i--) result *=i;
auto end_time = system_clock::now();
auto durationInMicroSeconds = duration_cast<microseconds>(end_time - start_time);
cout << "Looping " << number << " times took " << durationInMicroSeconds << "microseconds" << endl;

仅用于运动,这是一个简单的基于RAII的变体:

class Timer {
  public:
    explicit Timer(const string& name)
    : name_(name)
    , start_time_(system_clock::now()) {
    }
    ~Timer() {
      auto end_time = system_clock::now();
      auto durationInMicroSeconds = duration_cast<microseconds>(end_time - start_time);
      cout << "Timer: " << name << " took " << durationInMicroSeconds << "microseconds" << endl;
    }
  private:
    string name_;
    system_clock::time_point start_time_;
};

当然,这是更多的代码,但是一旦拥有,您可以相当有效地重复使用它:

{  
  Timer timer("loops");
  // your loop goes here:
  for (unsigned long i=number; i>=1; i--) result *=i;
}

如果您在执行程序代码中的循环语句中花费的时间尝试使用gettimeofday()如下,

#include <sys/time.h>
struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* Your loop code to execute here */
gettimeofday(&tv2, NULL);
printf("Time taken in execution = %f secondsn",
    (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
    (double) (tv2.tv_sec - tv1.tv_sec));

此解决方案更多地是针对C,可以在您的情况下用于计算所花费的时间。

这是lambda的完美情况。老实说,我不知道C 中的语法,但应该是这样的:

duration timer(function f) {
  auto start = system_clock::now();
  f();
  return system_clock::now() - start;
}

要使用它,您将代码包装在lambda中,然后将其传递给计时器。效果与@martin J.的代码非常相似。

duration code_time = timer([] () {
  // put any code that you want to time here
}
duration loop_time = timer([] () {
  for (unsigned long i=number; i>=1; i--) {
    result *=i;
  }
}