Example of obtaining ns in linux user space in nanoseconds

Source: Internet
Author: User
This article describes how to obtain ns in a linux user space in a matter of seconds. For more information, see

I. INTRODUCTION
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.

II. ns-level acquisition time of user space
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


Copy codeThe code is as follows:
Struct timespec
{
Time_t TV _sec;
Long int TV _nsec;
};

The sample code is as follows:


Copy codeThe code is as follows:
# Include
# Include
# Include
Int main (void)
{
Struct timespec time_start = {0, 0}, time_end = {0, 0 };
Clock_gettime (CLOCK_REALTIME, & time_start );
Printf ("start time % llus, % llu ns \ n", time_start. TV _sec, time_start. TV _nsec );
Clock_gettime (CLOCK_REALTIME, & time_end );
Printf ("endtime % llus, % llu ns \ n", time_end. TV _sec, time_end. TV _nsec );
Printf ("duration: % llus % lluns \ n", time_end. TV _sec-time_start. TV _sec, time_end. TV _nsec-time_start. TV _nsec );
Return 0;
}

Compile Command:


Copy codeThe code is as follows:
Gcc test. c-o test-lrt

Running result:


Copy codeThe code is as follows:
./Test
Start time 1397395863 seconds, 973618673 ns
Endtime 1397395863 s, 973633297 ns
Duration: 0 s 14624ns

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.