处理C++中执行时间的大量分析

Adr*_*ien 6 c++ performance time profiling

我目前正在研究涉及大量数据和复杂算法的科学计算项目,因此我需要进行大量的代码分析.我目前正依赖<ctime>clock_t计算代码的执行时间.我对这个解决方案非常满意......除了我基本上计时所有内容,因此对于我必须调用的每一行实际代码start_time_function123 = clock(), end_time_function123 = clock()以及cout << "function123 execution time: " << (end_time_function123-start_time_function123) / CLOCKS_PER_SEC << endl.这导致繁重的代码膨胀,并迅速使我的代码不可读.你会怎么处理?

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

Yak*_*ont 7

具有将代码标记为定时的RAII类型.

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

使用它:

void foo(){
  timed timer(__func__);
  // code
}
Run Code Online (Sandbox Code Playgroud)

噪音要小得多.

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