C# · 12月 20, 2021

linux C语言获取时间

微秒级: https://blog.csdn.net/zhubaohua_bupt/article/details/52873082

#include // for printf()

#include // for gettimeofday()

#include // for sleep()

int main()

{

struct timeval start,end;

gettimeofday( &start,NULL );

printf(“start : %d.%dn”,start.tv_sec,start.tv_usec);

sleep(1);

gettimeofday( &end,NULL );

printf(“end : %d.%dn”,end.tv_sec,end.tv_usec);

return 0;

}

纳秒级: https://www.cnblogs.com/kekukele/p/3662816.html

#include

#include

#include

int main(void)

{

struct timespec time_start={0,0},time_end={0,0};

clock_gettime(CLOCK_REALTIME,&time_start);

printf(“start time %llus,%llu nsn”,time_start.tv_sec,time_start.tv_nsec);

clock_gettime(CLOCK_REALTIME,&time_end);

printf(“end time %llus,time_end.tv_sec,time_end.tv_nsec);

printf(“duration:%llus %llunsn”,time_end.tv_sec-time_start.tv_sec,time_end.tv_nsec-time_start.tv_nsec);

return 0;

}

毫秒级: https://site.douban.com/199048/widget/notes/12005386/note/253542964/

#include

#include

#include

int main(){

clock_t start,finish;

double duration;

start = clock();

//run code

finish = clock();

duration = (double)(finish – start) / CLOCKS_PER_SEC;

printf( “%f secondsn”,duration );

return 0;

}

总结:https://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html

#include

#include

#include

#include

#include

#include

#define WAIT for(i=0;i<298765432;i++);

#define MILLION 1000000

int

main ( int argc,char *argv[] )

{

int i;

long ttt;

clock_t s,e;

struct tms aaa;

s=clock();

WAIT;

e=clock();

printf(“clock time : %.12fn”,(e-s)/(double)CLOCKS_PER_SEC);

long tps = sysconf(_SC_CLK_TCK);

s=times(&aaa);

WAIT;

e=times(&aaa);

printf(“times time : %.12fn”,(e-s)/(double)tps);

struct timeval tvs,tve;

gettimeofday(&tvs,NULL);

WAIT;

gettimeofday(&tve,NULL);

double span = tve.tv_sec-tvs.tv_sec + (tve.tv_usec-tvs.tv_usec)/1000000.0;

printf(“gettimeofday time: %.12fn”,span);

struct timespec tpstart;

struct timespec tpend;

clock_gettime(CLOCK_REALTIME,&tpstart);

WAIT;

clock_gettime(CLOCK_REALTIME,&tpend);

double timedif = (tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000000000.0;

printf(“clock_gettime time: %.12fn”,timedif);

return EXIT_SUCCESS;

}