In Linux programming, if time is used, you can use struct timeval to obtain the system time. The struct timeval function prototype is as follows:
Struct timeval {_ kernel_time_t TV _sec;/* seconds */_ kernel_suseconds_t TV _usec;/* microseconds */};
For example, to calculate the running time of a code, you can use the following code:
Int main () {struct timeval TV; long start_time, stop_time, delta_time; gettimeofday (& TV, null); start_time = TV. TV _usec; // your code heregettimeofday (& TV, null); stop_time = TV. TV _usec; delta_time = (stop_time-start_time + 1000000) % 1000000 ;}
Delta_time is the time for running your code, in milliseconds.
It is worth noting that the maximum value of TV _usec is 1000000, that is, 1 second. After it is recorded as 1000000, it starts from 0. Therefore, we add 1000000 to obtain the remainder of 1000000, solve the problem that delta_time is negative.