我希望计算API返回值所花费的时间.这种行动所花费的时间是纳秒秒.由于API是C++类/函数,我使用timer.h来计算相同的:
#include <ctime>
#include <cstdio>
using namespace std;
int main(int argc, char** argv) {
clock_t start;
double diff;
start = clock();
diff = ( std::clock() - start ) / (double)CLOCKS_PER_SEC;
cout<<"printf: "<< diff <<'\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了以秒为单位的时间.如何在毫秒秒内获得相同的精度?
在Windows下也有像一些方便的功能,QueryPerformanceCounter
从mmsystem.h
创建高分辨率定时器.Linux有类似的东西吗?
我知道clock()不提供挂钟时间,并且CLOCKS_PER_SEC是系统相关值。假设我不关心系统相关问题,我可以假设下面的代码在GNU/Linux和Windows 中总是等待 1 秒,因为我测试过它对我来说似乎没问题。还是我应该坚持使用依赖于系统的sleep()/usleep()函数?
void wait_a_sec()
{
clock_t start = clock();
do
{
// wait 1 sec
/**
* Second call to clock() gives the processor time in clock ticks
* since first call to it.
* CLOCKS_PER_SEC: clock ticks per sec.
*/
} while ( clock() < (start + CLOCKS_PER_SEC) );
}
Run Code Online (Sandbox Code Playgroud)