In software design, time processing is often used to calculate the execution time of statements and functions. In this case, time must be accurate to milliseconds or even a subtle time.
Int gettimeofday (struct timeval *TV, Struct timezone *TZ);
Int settimeofday (const struct timeval *TV , Const struct timezone *TZ);
Struct timeval {
Time_t TV _sec;/* seconds */
Suseconds_t TV _usec;/* microseconds */
};
Struct timezone {
Int tz_minuteswest;/* minutes west of Greenwich */
Int tz_dsttime;/* type of DST correction */
};
The following is a simple example for statistics.ProgramExecution time:
...
Struct timeval t_start, t_end;
Long cost_time = 0;
// Get start time
Gettimeofday (& t_start, null );
Printf ("Start Time: % LD us", t_start. TV _usec );
// Some operation
...
// Get End Time
Gettimeofday (& t_end, null );
Printf ("End Time: % LD us", t_end. TV _usec );
// Calculate Time Slot
Cost_time = t_end. TV _usec-t_start. TV _usec;
Printf ("cost time: % LD us", cost_time );
...
Output:
Start Time: 438061 us
End Time: 459867 us
Cost time: 21806 us
Demo:
# Include <stdio. h> # Include <Stdlib. h> # Include <Sys/time. h> Int Main ( Int Argc, Char *Argv []) {printf ( " Hello, world! \ N " ); Struct Timeval tvafter, tvpre; Struct Timezone TZ; Int Sum = 0 ; Int I = 0 ; Gettimeofday ( & Tvpre ,&Tz ); For (I = 0 ; I < 100000000 ; I ++ ) {Sum + = I;} gettimeofday ( & Tvafter ,& Tz); printf ( " Sum = % d elapsed time: % d \ n " , Sum, (tvafter. TV _sec-tvpre. TV _sec )* 1000 + (Tvafter. TV _usec-tvpre. TV _usec )/ 1000 ); Return Exit_success ;}