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.