I. How to Use the gettimeofday () function:
1. Introduction:
In C language, you can use the gettimeofday () function to get the time. Its precision can reach a subtle level
2. function prototype:
# Include <sys/time. h>
Int gettimeofday (struct timeval * TV, struct timezone * tz)
3. Description:
Gettimeofday () will return the current time using the TV struct, and put the information of the local time zone in the structure referred to by TZ
4. struct:
1> timeval
Struct timeval {
Long TV _sec;/* seconds */
Long TV _usec;/* subtle */
};
2> the timezone structure is defined:
Struct timezone {
Int tz_minuteswest;/* the time difference between Greenwich and */
Int tz_dsttime;/* type of DST correction */
}
3> In the gettimeofday () function, either TV or TZ can be empty. If it is null, the corresponding struct is not returned.
4> if the function is successfully executed, 0 is returned. If the function fails,-1 is returned. The error code is stored in errno.
5. program instance:
# Include <stdio. h>
# Include <sys/time. h>
# Include <unistd. h>
Int main ()
{
Struct timeval TV;
Struct timezone TZ;
Gettimeofday (& TV, & Tz );
Printf ("TV _sec: % d \ n", TV. TV _sec );
Printf ("TV _usec: % d \ n", TV. TV _usec );
Printf ("tz_minuteswest: % d \ n", tz. tz_minuteswest );
Printf ("tz_dsttime: % d \ n", tz. tz_dsttime );
}
Note: when using the gettimeofday () function, the second parameter is generally null, because we generally only get the current time, instead of getting the value of timezone
2. A common method for gettimeofday () Functions
When testing a program, you often need to know the time required for program execution. In Linux, you can use the gettimeofday function to get the time.
1. program instance:
Time required to test the call to the delya () function (unit: subtle)
# Include <stdio. h>
# Include <sys/time. h>
# Include <unistd. h>
Int delay (INT time)
{
Int I, J;
For (I = 0; I <time; I ++)
For (j = 0; j <5000; j ++)
;
}
Int main ()
{
Struct timeval start;
Struct timeval end;
Unsigned long diff;
Gettimeofday (& START, null );
Delay (10 );
Gettimeofday (& End, null );
Diff = 1000000 * (end. TV _sec-start. TV _sec) + end. TV _usec-start. TV _usec;
Printf ("thedifference is % LD \ n", diff );
Return 0;
}
Note:
This method can be used to detect the time used to call the delay () function.