Linux get millisecond-level time

Source: Internet
Author: User

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 ;} 

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.