time(),gettimeofday()及GetTickCount()效率比较

上一篇不知是什么时候的帖子,linux改进了gettimeofday之后的测试,三者相差无几

#include<iostream>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
using namespace std;
#define TEST_LOOPS 10000000

unsigned long getTickCount() const
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);

return (ts.tv_sec * 1000000 + ts.tv_nsec / 1000);
}

int main()
{
time_t tm; 
struct timeval tv1, tv2, tv_test;
int i;
gettimeofday(&tv1, NULL);
for(i = 0; i < TEST_LOOPS; i ++) 
{   
    gettimeofday(&tv_test, NULL);
}   
gettimeofday(&tv2, NULL);
cout << "run gettimeofday 10000000 times, used " << (tv2.tv_sec - tv1.tv_sec) * 1000000 +  tv2.tv_usec - tv1.tv_usec << " usec." << endl;

gettimeofday(&tv1, NULL);
for(i = 0; i < TEST_LOOPS; i ++) 
{   
    time(&tm);
}   
gettimeofday(&tv2, NULL);
cout << "run time 10000000 times, used " << (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec << " usec." << endl;

struct timespec ts; 
gettimeofday(&tv1, NULL);
for(i = 0; i < TEST_LOOPS; i ++) 
{   
    clock_gettime(CLOCK_MONOTONIC, &ts);
}   
gettimeofday(&tv2, NULL);
cout << "run tclock_gettime 10000000 times, used " << (tv2.tv_sec - tv1.tv_sec) * 1000000 + tv2.tv_usec - tv1.tv_usec << " usec." << endl;

return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_42651205/article/details/83028445