什么是在linux中测试程序性能的最佳方法

时间:2013-07-20 14:01:33

标签: linux c++11

假设我编写了一个程序,然后我为代码做了一些“优化”。 在我的例子中,我想测试C ++ 11中新功能std::move可以提高程序性能的程度。 我想检查“优化”是否有意义。

目前我通过以下步骤测试它:

  1. 编写程序(不含std::move),编译,获取二进制文件m1
  2. 优化它(使用std::move),编译,获取二进制文件m2
  3. 使用命令“time”来比较耗时:

    time ./m1 ; time ./m2
    
  4. 编辑:

    为了获得统计结果,需要进行数千次测试。

    有没有更好的方法可以做到这一点,还是有一些工具可以帮助它?

2 个答案:

答案 0 :(得分:1)

通常使用简单的时间比较来测量性能,例如endTime-beginTime总是一个好的开始,粗略估计。

稍后您可以使用 profiler ,例如 Valgrind 来衡量程序的不同部分的执行情况。

通过分析,您可以测量程序的空间(内存)或时间复杂度,特定指令的使用或函数调用的频率/持续时间。

如果您想使用GUI进行更高级的分析功能,还有AMD CodeAnalyst。它是免费/开源的。

答案 1 :(得分:0)

有几种工具(包括其他工具)可以为您进行分析:

其中一些需要特定的编译方式或特定的编译器。其中一些人特别擅长分析给定的处理器架构(AMD / Intel ......)。

由于您似乎可以访问C ++ 11,并且如果您只想测量某些时间,可以使用std::chrono

#include <chrono>
#include <iostream>
class high_resolution_timer
{
private:
  typedef std::chrono::high_resolution_clock clock;
  clock::time_point m_time_point;
public:
  high_resolution_timer (void) 
    : m_time_point(clock::now()) { }
  void restart (void) 
  { 
    m_time_point = clock::now(); 
  }
  template<class Duration>
  Duration stopover (void) 
  { 
    return std::chrono::duration_cast<Duration>
           (clock::now()-m_time_point);  
  }
}; 

int main (void)
{
  using std::chrono::microseconds;
  high_resolution_timer timer;

  // do stuff here

  microseconds first_result = timer.stopover<microseconds>();
  timer.restart();

  // do other stuff here

  microseconds second_result = timer.stopover<microseconds>();

  std::cout << "First took " << first_result.count() << " x 10^-6;";
  std::cout << " second took " << second_result.count() << " x 10^-6.";
  std::cout << std::endl;

}

但是你应该意识到优化几毫秒的整体运行时几乎没有任何意义(如果你的程序运行时间> = 1s)。您应该在代码中计算高度重复的事件(如果有的话,或者至少是那些瓶颈)。如果这些显着改善(这可能是毫秒或微秒),您的整体表现也可能会提高。

相关问题