Gettimeofday and clock_gettime are different.

Source: Internet
Author: User

Clock_gettime is more accurate than gettimeofday

Perform a simple test and use clock_gettime to perform the test.
Test. c

#include<time.h>
#include<stdio.h>

#define MILLION 1000000

int main(void)
{
        struct timespec tpstart;
        struct timespec tpend;
        long timedif;

        clock_gettime(CLOCK_MONOTONIC, &tpstart);
        clock_gettime(CLOCK_MONOTONIC, &tpend);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        fprintf(stdout, "it took %ld microseconds/n", timedif);

        return 0;
}

Under Linux 2.6 kernel
Gcc-O test. C-LRT
./Test
Expected result:
It took 2 microseconds
Use gettimeofday to perform the test.

#include<time.h>
#include<stdio.h>

#define MILLION 1000000

int main(void)
{
        struct timespec tpstart;
        struct timespec tpend;
        long timedif;

        gettimeofday(&tpstart, NULL);
        gettimeofday(&tpend, NULL);
        timedif = MILLION*(tpend.tv_sec-tpstart.tv_sec)+(tpend.tv_nsec-tpstart.tv_nsec)/1000;
        fprintf(stdout, "it took %ld microseconds/n", timedif);

        return 0;
}

Gcc-O test. c
./Test
Expected result:
It took 0 microseconds AIX also gets the same result

In addition, we can use the clock_gettime function to test that the 64-bit program runs faster than the 32-bit program.
On AIX p570, 16 machines with CPU 15.5g memory tested
The result obtained in 64-Bit mode is 0 microseconds.
The result of the 32-Bit mode is 1 microsecond.

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.