How to detect if RDTSC returns a constant rate counter value?

不问归期 提交于 2019-12-01 20:11:41

You can use CPUID to tell you. From the docs on CPUID Fn8000_0007_EDX bit 8:

TscInvariant: TSC invariant. The TSC rate is ensured to be invariant across all P-States, C-States, and stop grant transitions (such as STPCLK Throttling); therefore the TSC is suitable for use as a source of time. 0 = No such guarantee is made and software should avoid attempting to use the TSC as a source of time.

I know it's a long time since the original question was asked, but can I just point out that checking the generation/model of the processor is absolutely the WRONG thing to do. First of all, it's very easy to get the code wrong so that it doesn't work on future generation processors (because the family/model numbers aren't always "linear"), and secondly, just because a processor is "a later family/model" than the ones you knew this works on, it's not a guarantee that the feature is there. It's LIKELY, but I've seen plenty of code that does this badly, and thus "new processor comes out, and the code gets things wrong".

Use the CPUID bit to check if the processor has the correct bit or not.

just use CPUID to detect the generation of the CPU, see if its using constant counters. I'd however, suggest using a profiling API instead though, something like AMD's codeanalyst sdk would do well

I do count the number o ticks in a second and then compare to the informed clock at /proc/cpuinfo. It only works with dynamic clock disabled. See the source: https://github.com/petersenna/rdtscbench

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!