A brief analysis of the precise time control function under Linux

  • 2020-04-02 01:08:43
  • OfStack

It's ok to just test the time, but if the program USES a function of the time control class, like time,  Gettimeofday itself also consumes a lot of time and increases the cost of program execution, so the resulting time is not accurate.
In this case, the function of CPU heartbeat is used to process the time.

Disadvantages: some machines may not support the use of CPU heartbeat RDTSCPLL function due to hardware reasons, generally not on virtual machines.
 
Usage: When I was doing the set-top box test tool, I used this method to control the number of users connected per second (100 users connected per second), and the test effect was relatively ideal, basically, there were 100 users online every 1 second.

Paste the function code below:

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <asm/msr.h>
long long g_var_llOneSecJiffiesCount = 0;
long long GetCurCpuHopCount()
{
        long long llcurrentcpuhopcount;
        int iaux;
        rdtscpll(llcurrentcpuhopcount,iaux);
        return llcurrentcpuhopcount;
}
int main(int argc, char* argv[])
{
        long long llstartvalue = 0;
        long long llendvalue = 0;
        struct timeval starttm,endtm;
        int iaux = 0;
        gettimeofday(&starttm,NULL);
        rdtscpll(llstartvalue,iaux);
        sleep(3);
        rdtscpll(llendvalue,iaux);
        gettimeofday(&endtm,NULL);
        g_var_llOneSecJiffiesCount = ((llendvalue-llstartvalue)*1000000/(endtm.tv_sec*1000000-starttm.tv_sec*1000000+endt
m.tv_usec-starttm.tv_usec));//Use a heartbeat instead
        long long begin_time = GetCurCpuHopCount();
        sleep(100);//There are some functions that can be tested
        long long end_time = GetCurCpuHopCount();
        long long use_time = (end_time - begin_time) * 1000000 / g_var_llOneSecJiffiesCount;
        printf(" Testing a feature  use time(us): %lldn",use_time);
        return 0;
}

Execution results:
Test a function use time(us): 100,002,362
Conclusion: the results are satisfactory. The error is so small that we can ignore it.

Related articles: