这个代码如何计算经过的CPU周期数?

前端之家收集整理的这篇文章主要介绍了这个代码如何计算经过的CPU周期数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this SO thread开始,该代码计算行// 1和// 2之间运行代码cpu周期数.
$cat cyc.c 
#include<stdio.h>

static __inline__ unsigned long long rdtsc(void)
{
  unsigned long long int x;
     __asm__ volatile (".byte 0x0f,0x31" : "=A" (x));
     return x;
}

int main() {
    unsigned long long cycles = rdtsc(); //1
    cycles = rdtsc() - cycles;           //2
    printf("Time is %d\n",(unsigned)cycles);
    return 0;
}

$gcc cyc.c -o cyc
$./cyc
Time is 73
$./cyc
Time is 74
$./cyc
Time is 63
$./cyc
Time is 73
$

rdtsc()函数如何工作?

解决方法

函数执行x86指令RTDSC,它的操作码为0x0f,0x31.处理器内部跟踪时钟周期,并读取该数字.

当然,这只适用于x86 procs,其他处理器将需要不同的指令.

The Time Stamp Counter is a 64-bit register present on all x86 processors since the Pentium. It counts the number of ticks since reset. Instruction RDTSC returns the TSC in EDX:EAX. Its opcode is 0F 31.[1] Pentium competitors such as the Cyrix 6×86 did not always have a TSC and may consider RDTSC an illegal instruction. Cyrix included a Time Stamp Counter in their MII.

http://en.wikipedia.org/wiki/Time_Stamp_Counter

原文链接:https://www.f2er.com/c/112731.html

猜你在找的C&C++相关文章