Under the Unix/linux system, the Gettimeofday function is used to obtain the timestamp of the current system, which can reach a microsecond (microsecond, or μs) level.
The information for the current timestamp is stored through the struct Timeval:
#ifndef _struct_timeval #define _struct_timeval STRUCT timeval_struct_timeval{ __darwin_time_t tv_sec; /* */ __darwin_suseconds_t tv_usec ; /* */}; #endif /* _struct_timeval */
Where tv_sec is used to hold the current timestamp of the number of seconds, generally a long type, tv_usec is used to hold the current timestamp of the number of microseconds, generally int type.
This structure and the Gettimeofday function are declared in the <sys/time.h> header file.
Here's an example:
#include <sys/time.h>intMainvoid){ structtimeval Tbegin, tEnd; Gettimeofday (&Tbegin, NULL); intCount =0; for(inti =0; I < +* +; i++) Count+=i; Gettimeofday (&tEnd, NULL); LongDeltatime =1000000L* (TEND.TV_SEC-TBEGIN.TV_SEC) + (Tend.tv_usec-tbegin.tv_usec); printf ("Time spent:%ldus\n", deltatime);}
In the preceding code, gettimeofday (&tbegin, NULL) is used to obtain the timestamp before the calculation, while gettimeofday (&tend, NULL) is used to obtain the timestamp after the calculation. Then deltatime can get the number of microseconds between two timestamps. Finally, the result is output.
Time stamp function obtained under Unix/linux system