Linux user space to obtain ns at the nanosecond level

Source: Internet
Author: User

When testing program performance, we often need to obtain precise ns-level time to measure the performance of a program. The following describes how to obtain ns-level time in linux.

Use the clock_gettime function. The function prototype is as follows:

Long sys_clock_gettime (clockid_t which_clock, struct timespec * tp );

1. which_clock parameter explanation

CLOCK_REALTIME

CLOCK_MONOTONIC: Timing starts from the moment when the system is started, and is not affected by changes in the system time.

CLOCK_PROCESS_CPUTIME_ID: time spent by the current process to the CPU of the current Code System

CLOCK_THREAD_CPUTIME_ID: time spent by the current thread to the CPU of the current Code System

2. struct timespec Structure

 

The sample code is as follows:

# Include <stdio. h> <stdlib. h> <time. h> main (timespec time_start = {,}, time_end = {,&, time_end. TV _sec-time_start. TV _sec, time_end. TV _nsec-

 

Compile command:

Gcc test. c-o test-lrt

Running result:

./

The running result shows that it takes about 15 us to call the printf () function at a time.

 

Related Article

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.