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.