在 C++ 中处理大量的执行时间分析 [英] Dealing with heavy profiling of execution times in C++

查看:96
本文介绍了在 C++ 中处理大量的执行时间分析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个涉及大量数据和复杂算法的科学计算项目,因此我需要进行大量代码分析.我目前依靠 clock_t 来计时我的代码的执行.我对这个解决方案非常满意......除了我基本上对所有内容进行计时,因此对于每一行真实代码我必须调用 start_time_function123 = clock(), end_time_function123 = clock()cout <<"function123 执行时间:" <<(end_time_function123-start_time_function123)/CLOCKS_PER_SEC <<结束.这会导致严重的代码膨胀并很快使我的代码变得不可读.你会怎么处理?

I'm currently working on a scientific computing project involving huge data and complex algorithms, so I need to do a lot of code profiling. I'm currently relying on <ctime> and clock_t to time the execution of my code. I'm perfectly happy with this solution... except that I'm basically timing everything and thus for every line of real code I have to call start_time_function123 = clock(), end_time_function123 = clock() and cout << "function123 execution time: " << (end_time_function123-start_time_function123) / CLOCKS_PER_SEC << endl. This leads to heavy code bloating and quickly makes my code unreadable. How would you deal with that?

我能想到的唯一解决方案是找到一个 IDE,允许我标记代码的一部分(在不同的位置,甚至在不同的文件中),并通过一个按钮切换隐藏/显示所有标记的代码.这将允许我在大部分时间隐藏与分析相关的代码部分,并仅在我想要的时候显示它.

The only solution I can think of would be to find an IDE allowing me to mark portions of my code (at different locations, even in different files) and to toggle hide/show all marked code with one button. This would allow me to hide the part of my code related to profiling most of the time and display it only whenever I want to.

推荐答案

有一个 RAII 类型,将代码标记为定时.

Have a RAII type that marks code as timed.

struct timed {
  char const* name;
  clock_t start;
  timed( char const* name_to_record):
    name(name_to_record),
    start(clock())
  {}
  ~timed(){
    auto end=clock();
    std::cout << name << " execution time: " << (end-start) / CLOCKS_PER_SEC << std::endl;
  }
};

使用它:

void foo(){
  timed timer(__func__);
  // code
}

噪音小得多.

您可以使用基于非作用域的完成操作进行扩充.在进行大量分析时,有时我喜欢包含唯一的 id.将 cout 与 endl 一起使用可能会导致它支配时间;以异步方式转储到大缓冲区的快速记录可能是最佳的.如果你需要计时毫秒级的时间,甚至应该避免分配、锁和字符串操作.

You can augment with non-scope based finish operations. When doing heavy profiling sometimes I like to include unique ids. Using cout esoecially with endl could result in it dominating timing; fast recording to a large buffer that is dumped out in an async manner may be optimal. If you need to time ms level time, even allocation, locks and string manipulation should be avoided.

这篇关于在 C++ 中处理大量的执行时间分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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