获取 cpu 时钟周期数(cpu cycle)

1、x86下获取cpu 时钟周期数

get_cpu_cycle:函数获取自cpu启动以来所记录的cpu时钟周期数。

1.1 实验代码

#include <stdio.h>
#include <unistd.h>

int main()
{
    unsigned long long number = 100000;
    unsigned long long tsc0;
    unsigned long long tsc1;
    unsigned long long reth1;
    unsigned long long retl0;

    unsigned long long get_cpu_cycle()
    {
        __asm__ __volatile__(
        "rdtsc" :
        "=d" (reth1),
        "=a" (retl0)
        );
        return ((reth1 << 32)|(retl0));
    }

    tsc0 = get_cpu_cycle();
    while(number--)
    {
        __asm__ __volatile__("nop");
    }
    tsc1 = get_cpu_cycle();

    printf("%llx-%llx\n", reth1, retl0);
    printf("%llu-%llu=%llu\n", tsc0, tsc1, tsc1-tsc0);

    return 0;
}

 1.2 rdtsc 指令

参考:

rdtsc指令使用:https://www.felixcloutier.com/x86/rdtsc

rdstc指令弊端以及解决办法:https://blog.csdn.net/solstice/article/details/5196544

 

rdtsc指令:将cpu的时间戳计数(保存在64位的MSR中)读取到EDX:EAX两个寄存器中。

EDX寄存器:存放高32位数据

EAX寄存器:存放低32位数据

cpu cycle和时间关系:

cpu从启动到目前为止运行的时间time = 1/频率 * cpu_cycle

查看某cpu的频率:cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq

rdstc指令弊端:在多核上,可能cpu_cycle不一致,故统计时需注意尽可能在同一个核上比较。cpu乱序执行会导致你想测试几条指令,实际执行被时候被优化了,多执行了很多指令或者没执行那么多。

 

 1.2 arm 获取cpu 时钟周期个数

1.2.1 内核态:

static uint64_t Rdtsc() 

{ 

uint64_t count_num; 

__asm__ __volatile__ ("mrs %0, PMCCNTR_EL0" : "+r" (count_num)); 

return count_num;

}

1.2.1 用户态:

注意:ARM某芯片用户态读取cpu cycle为100MHZ,所以每一个cycle对应为10ns(注意可能每款芯片晶振不一样,即可能不是100MHZ)

unsigned long long tsc = 0;
asm volatile("mrs %0, cntvct_el0" : "=r"(tsc));

 

参考x86和arm获取方法:https://support.huaweicloud.com/pinsrcase-kunpengprocs/kunpengprocessor_18_0014.html

参考华为社区:https://bbs.huaweicloud.com/blogs/126968

      :https://support.huaweicloud.com/pinsrcase-kunpengprocs/kunpengprocessor_18_0014.html

arm用户态cpu_cycle以及时钟频率:https://bbs.csdn.net/topics/600329178

 

posted on 2022-04-26 19:28  红旗kernel  阅读(5269)  评论(0)    收藏  举报

导航