Getting an accurate execution time in C++ (micro seconds)

后端 未结 4 838
温柔的废话
温柔的废话 2020-12-13 06:37

I want to get an accurate execution time in micro seconds of my program implemented with C++. I have tried to get the execution time with clock_t but it\'s not accurate.

4条回答
  •  难免孤独
    2020-12-13 06:57

    If you are looking how much time is consumed in executing your program from Unix shell, make use of Linux time as below,

    time ./a.out 
    
    real    0m0.001s
    user    0m0.000s
    sys     0m0.000s
    

    Secondly if you want time took in executing number of statements in the program code (C) try making use of gettimeofday() as below,

    #include 
    struct timeval  tv1, tv2;
    gettimeofday(&tv1, NULL);
    /* Program code to execute here */
    gettimeofday(&tv2, NULL);
    printf("Time taken in execution = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));
    

提交回复
热议问题