linux C語言獲取時間

  1. 微秒級: https://blog.csdn.net/zhubaohua_bupt/article/details/52873082
#include <stdio.h>        // for printf()
#include <sys/time.h>    // for gettimeofday()
#include <unistd.h>        // for sleep()

int main()
{
    struct timeval start, end;
    gettimeofday( &start, NULL );
    printf("start : %d.%d\n", start.tv_sec, start.tv_usec);
    sleep(1);
    gettimeofday( &end, NULL );
    printf("end   : %d.%d\n", end.tv_sec, end.tv_usec);

    return 0;
}
  1. 納秒級: https://www.cnblogs.com/kekukele/p/3662816.html
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
   struct timespec time_start={0, 0},time_end={0, 0};
   clock_gettime(CLOCK_REALTIME, &time_start);
   printf("start time %llus,%llu ns\n", time_start.tv_sec, time_start.tv_nsec);
   clock_gettime(CLOCK_REALTIME, &time_end);
   printf("end   time %llus,%llu ns\n", time_end.tv_sec, time_end.tv_nsec);
   printf("duration:%llus %lluns\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec);
   return 0;
}
  1. 毫秒級: https://site.douban.com/199048/widget/notes/12005386/note/253542964/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
   clock_t start, finish;
   double  duration;

   start = clock();
    //run code
   finish = clock();
   
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "%f seconds\n", duration );
   
   return 0;
}
  1. 總結:https://www.cnblogs.com/krythur/archive/2013/02/25/2932647.html
    在這裏插入圖片描述
#include    <stdio.h>
#include    <stdlib.h>
#include    <unistd.h>
#include    <time.h>
#include    <sys/times.h>
#include    <sys/time.h>
#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 : %.12f\n",(e-s)/(double)CLOCKS_PER_SEC);


    long tps = sysconf(_SC_CLK_TCK);
    s=times(&aaa);
    WAIT;
    e=times(&aaa);
    printf("times time : %.12f\n",(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: %.12f\n",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: %.12f\n", timedif);

    return EXIT_SUCCESS;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章