注意:该作者博客已迁移至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;
}