轻松测量经过的时间

新手上路,请多包涵

我正在尝试使用 time() 来测量程序的各个点。

我不明白的是为什么之前和之后的值是一样的?我知道这不是分析我的程序的最佳方式,我只是想看看需要多长时间。

 printf("**MyProgram::before time= %ld\n", time(NULL));

doSomthing();
doSomthingLong();

printf("**MyProgram::after time= %ld\n", time(NULL));

我努力了:

 struct timeval diff, startTV, endTV;

gettimeofday(&startTV, NULL);

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL);

timersub(&endTV, &startTV, &diff);

printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);

如何读取 **time taken = 0 26339 的结果?这是否意味着 26,339 纳秒 = 26.3 毫秒?

**time taken = 4 45025 怎么样,这是否意味着 4 秒和 25 毫秒?

原文由 hap497 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 421
1 个回答

这是一个简单的类,它将以指定的持续时间单位打印它进入和超出范围的时间之间的持续时间:

 #include <chrono>
#include <iostream>

template <typename T>
class Benchmark
{
   public:
    Benchmark(std::string name) : start(std::chrono::steady_clock::now()), name(name) {}
    ~Benchmark()
    {
        auto end = std::chrono::steady_clock::now();
        T duration = std::chrono::duration_cast<T>(end - start);
        std::cout << "Bench \"" << name << "\" took: " << duration.count() << " units" << std::endl;
    }

   private:
    std::string name;
    std::chrono::time_point<std::chrono::steady_clock> start;

};
int main()
{
  Benchmark<std::chrono::nanoseconds> bench("for loop");
  for(int i = 0; i < 1001000; i++){}
}

示例用法:

 int main()
{
  Benchmark<std::chrono::nanoseconds> bench("for loop");
  for(int i = 0; i < 100000; i++){}
}

输出:

 Bench "for loop" took: 230656 units

原文由 SickGuy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题