加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:00:24 所属栏目:百科 来源:网络整理
导读:从 this SO thread开始,该代码计算行// 1和// 2之间运行代码的CPU周期数. $cat cyc.c #includestdio.hstatic __inline__ unsigned long long rdtsc(void){ unsigned long long int x; __asm__ volatile (".byte 0x0f,0x31" : "=A" (x)); return x;}int main(
从 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 %dn",(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读