简体   繁体   English

如何确定时间戳计数器(TSC)重置了多少次

[英]How to determine how many times Time Stamp Counter (TSC) is reset

I need to measure time based on Time Stmp Counter (TSC) for some reasons. 由于某些原因,我需要基于时标计数器(TSC)测量时间。 To read TSC, I am using the code below: 要阅读TSC,我正在使用以下代码:

#include <stdio.h>
#include <inttypes.h>

inline volatile uint32_t RDTSC32() {
    register uint32_t TSC asm("eax");
    asm volatile (".byte 15, 49" : : : "eax", "edx");
    return TSC;
}

inline volatile uint64_t RDTSC64() {
    register uint64_t TSC asm("rax");
    asm volatile (".byte 15, 49" : : : "rax", "rdx");
    return TSC;
} 

int main() {
    while (1) {
        printf("%" PRIu64 "\n", RDTSC64());
    }
} 

When I've tested it, it works fine. 经过测试后,它可以正常工作。 Except one thing. 除了一件事。 When it reaches the maximum counter value (some value higher than 4,256,448,731, in my environment,) the counter value gets reset to 0 and keeps going on. 当它达到最大计数器值(在我的环境中,某些值大于4,256,448,731)时,计数器值将重置为0并继续运行。

In this situation, is there any way to see how many times TSC has been reset? 在这种情况下,是否有任何方法可以查看已重置TSC多少次?

For example, the code below does not print a correct time difference: 例如,下面的代码不能显示正确的时差:

#include <stdio.h>

int main() {
    long long start, end;
    start = RDTSC64();
    // long long works to do
    end = RDTSC64();
    printf("%lld \n", end - start);
} 

The time stamp counter is always 64-bit, see this statement on the Wipedia page : 时间戳记计数器始终为64位,请参见Wipedia页面上的以下语句:

The Time Stamp Counter (TSC) is a 64-bit register present on all x86 processors since the Pentium. 自奔腾以来,时间戳计数器(TSC)是所有x86处理器上存在的64位寄存器。

For some reason you're getting a truncated value with only 32 bits, which is why it wraps. 由于某种原因,您得到的截断值只有32位,这就是为什么它会自动换行。 The 64-bit value will need 146 years of continuous counting at 4 GHz to wrap. 要封装64位值,需要在4 GHz上进行146年的连续计数。

Your code seems to want to use both eax and edx to hold the two 32 bit halves, as expected. 您的代码似乎想要像预期的那样同时使用eaxedx来保持两个32位的一半。 Something must go wrong when moving the values to the single C variable. 将值移到单个C变量时,一定会出错。 I believe the snippet you're using is for GCC; 我相信您使用的代码段是针对GCC的; perhaps that's no longer your compiler? 也许那不再是您的编译器了?

Inspect the generated assembly, and check the compiler docs for a proper intrinsic function instead. 检查生成的程序集,然后检查编译器文档中适当的内在函数。 This question has some good answers, with compiler-specific assembly. 这个问题对于特定于编译器的程序集有很好的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM