写一个C++性能测试类,测试一段代码运行时间

    xiaoxiao2022-07-06  204

    注意:该作者博客已迁移至https://buxianshan.xyz

    原理很简单,定义一个Stopwatch类,重写它的构造函数和析构函数,根据调用构造函数和析构函数的时间差获得所用时间。只需要用{ }把要测试的代码括起来,在第一行创建一个Stopwatch类的对象就可以了。 例子:

    #include <time.h> #include <iostream> using namespace std; class Stopwatch{ public: Stopwatch() : start(clock()){} //构造函数,创建对象便开始计时 ~Stopwatch(); private: clock_t start; }; Stopwatch::~Stopwatch(){ clock_t total = clock()-start; //析构函数和构造函数的时间差即为所用时间 cout<<"此操作所用时间:"<<total<<"ms"; } int main(){ { Stopwatch watch; // 开始计时 string *pstr[10000]; for (int i=0;i<10000;i++){ pstr[i] = new string("Life is short, you need Python."); } } // 摧毁计时器并报告结果 return 0; }
    最新回复(0)