Test code run time
<sys/time.h> in Linux has a function to get the current time, accurate to microseconds----> gettimeofday ()
1#include <sys/time.h> // int gettimeofday (struct timeval *tv, struct timezone *tz);2 /*********************************************3 * struct Timeval4 * {5 * time_t tv_sec; Seconds6 * suseconds_t tv_usec; Microseconds: microsecond 10^ ( -6) s, where the tv_sec is in microseconds7 *//Millisecond: Ms 10^ ( -3) s8 * }9 **********************************************Ten * struct TimeZone One * { A * int tz_minuteswest; Minutes west of Greenwich - * int tz_dsttime; Type of DST correction - * } the **********************************************/
When used, define two struct timeval variables (usually the second parameter of the Gettimeofday () is set to NULL), save the time before and after the code test, and finally subtract, to get the code run time (can be converted to the time you need).
1#include <stdio.h>2#include <sys/time.h>//For Gettimeofday ()3#include <string.h>//For memset ()4 5 intMain ()6 {7 inti =10000000;8 struct timeval start, end;//define 2 struct Timeval variables9 Ten //------------------------- One gettimeofday (&start, NULL);//get the beginning time A //------------------------- - - //Test Code the while(i) - { -i--; - } + - //------------------------- + gettimeofday (&end, NULL);//Get the end time A //------------------------- at - Long LongTotal_time = (end.tv_sec-start.tv_sec) *1000000+ (END.TV_USEC-START.TV_USEC);//get the Run time by microsecond -printf"Total time is %lld us\n", total_time); -Total_time/= +;//get the run time by millisecond -printf"Total time is %lld ms\n", total_time); -}
Test Result: (CentOS 6.5, gcc 4.4.7)
Total time is 49658 us
Total time is MS