Time stamp function obtained under Unix/linux system

Source: Internet
Author: User

Under the Unix/linux system, the Gettimeofday function is used to obtain the timestamp of the current system, which can reach a microsecond (microsecond, or μs) level.

The information for the current timestamp is stored through the struct Timeval:

#ifndef _struct_timeval #define _struct_timeval        STRUCT timeval_struct_timeval{    __darwin_time_t         tv_sec;          /*  */    __darwin_suseconds_t    tv_usec        ; /* */}; #endif /* _struct_timeval */

Where tv_sec is used to hold the current timestamp of the number of seconds, generally a long type, tv_usec is used to hold the current timestamp of the number of microseconds, generally int type.

This structure and the Gettimeofday function are declared in the <sys/time.h> header file.

Here's an example:

#include <sys/time.h>intMainvoid){        structtimeval Tbegin, tEnd; Gettimeofday (&Tbegin, NULL); intCount =0;  for(inti =0; I < +* +; i++) Count+=i; Gettimeofday (&tEnd, NULL); LongDeltatime =1000000L* (TEND.TV_SEC-TBEGIN.TV_SEC) + (Tend.tv_usec-tbegin.tv_usec); printf ("Time spent:%ldus\n", deltatime);}

In the preceding code, gettimeofday (&tbegin, NULL) is used to obtain the timestamp before the calculation, while gettimeofday (&tend, NULL) is used to obtain the timestamp after the calculation. Then deltatime can get the number of microseconds between two timestamps. Finally, the result is output.

Time stamp function obtained under Unix/linux system

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.