How to use function to get ns level time under Linux

  
                

When doing Linux system operation, because the test program performance needs, the time must be accurate to the ns level, then how to achieve it? The following small series teaches you how to use the function to achieve the Linux user space ns level time acquisition, let's learn together.

I. Introduction

We often need to obtain precise time ns level of performance test procedures to measure performance when a program described below under linux user space to get ns Level time method

Second, user space to get ns level time

Using 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: The system real-time time changes with the real-time time of the system, that is, starting from UTC1970-1-1 0:0:0, if the system is in the middle moment The time is changed by the user, and the corresponding time changes accordingly

CLOCK_MONOTONIC: Starts from the moment the system is started, and is not affected by the system time being changed by the user

CLOCK_PROCESS_CPUTIME_ID: This process is Time spent by the current code system CPU

CLOCK_THREAD_CPUTIME_ID: time spent by the thread to the current code system CPU

2.struct timespec structure

The code is as follows:

struct timespec

{

time_t tv_sec;

long int tv_nsec;

} ;

The sample code is as follows:

The code is as follows:

#include"stdio.h"

#include"stdlib.h"

#include《time.h》

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\ ”, time_start.tv_sec, time_start.tv_nsec);

clock_gettime(CLOCK_REALTIME, &time_end);

printf(“endtime %llus,%llu ns\ ”, time_end.tv_sec, time_end.tv_nsec);

printf (&duquo;duration:%llus %lluns\ ”, time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec);

return 0;

}

Compile command:

The code is as follows:

gcc test.c -o test -lrt

Running result:

The code is as follows:

. /test

start time 1397395863s,973618673 ns

endtime 1397395863s,973633297 ns

duration:0s 14624ns

From the running results you can see that printf is called ( The function needs about 15us at a time.

The above is a method for obtaining ns-level time using functions under Linux. If you need to be accurate to ns-level time in the test program performance, you can try the method described in this article. Not very simple?

Copyright © Windows knowledge All Rights Reserved