Struct timeval timing problem

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.