Calculate system time using rdtsc

后端 未结 2 1410
栀梦
栀梦 2020-12-03 09:08

Suppose all the cores in my CPU have same frequency, technically I can synchronize system time and time stamp counter pairs for each core every millisecond or so. Then based

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 09:58

    Don't do that -using yourself directly the RDTSC machine instruction- (because your OS scheduler could reschedule other threads or processes at arbitrary moments, or slow down the clock). Use a function provided by your library or OS.

    My main objective is to avoid the need to perform system call every time I want to know the system time

    On Linux, read time(7) then use clock_gettime(2) which is really quick (and does not involve any slow system call) thanks to vdso(7).

    On a C++11 compliant implementation, simply use the standard header. And standard C has clock(3) (giving microsecond precision). Both would use on Linux good enough time measurement functions (so indirectly vdso)

    Last time I measured clock_gettime it often took less than 4 nanoseconds per call.

提交回复
热议问题