【发布时间】:2019-10-05 14:26:16
【问题描述】:
我正在尝试计算运行单个 ASM 指令所需的 CPU 周期数。为了做到这一点,我创建了这个函数:
measure_register_op:
# Calculate time of required for movl operation
# function setup
pushl %ebp
movl %esp, %ebp
pushl %ebx
pushl %edi
xor %edi, %edi
# first time measurement
xorl %eax, %eax
cpuid # sync of threads
rdtsc # result in edx:eax
# we are measuring instuction below
movl %eax, %edi
# second time measurement
cpuid # sync of threads
rdtsc # result in edx:eax
# time difference
sub %eax, %edi
# move to EAX. Value of EAX is what function returns
movl %edi, %eax
# End of function
popl %edi
popl %ebx
mov %ebp, %esp
popl %ebp
ret
我在 *.c 文件中使用它:
extern unsigned int measure_register_op();
int main(void)
{
for (int a = 0; a < 10; a++)
{
printf("Instruction took %u cycles \n", measure_register_op());
}
return 0;
}
问题是:我看到的值太大了。我现在收到3684414156。这里可能出了什么问题?
编辑:
从 EBX 更改为 EDI,但结果仍然相似。它必须与 rdtsc 本身有关。在调试器中,我可以看到第二个测量结果为 0x7f61e078 和第一个 0x42999940,减法后仍然给出 1019758392
编辑: 这是我的生成文件。也许我编译不正确:
compile: measurement.s measurement.c
gcc -g measurement.s measurement.c -o ./build/measurement -m32
编辑: 这是我看到的确切结果:
Instruction took 4294966680 cycles
Instruction took 4294966696 cycles
Instruction took 4294966688 cycles
Instruction took 4294966672 cycles
Instruction took 4294966680 cycles
Instruction took 4294966688 cycles
Instruction took 4294966688 cycles
Instruction took 4294966696 cycles
Instruction took 4294966688 cycles
Instruction took 4294966680 cycles
【问题讨论】:
-
您总是得到错误的结果还是只是有时?尝试将您的线程固定到单个 CPU。
-
@fuz 是的,我总是得到大约 10 个数字
-
@fuz 你能告诉我怎么做吗?
-
@Piotrek 这看起来像个垃圾
uint32_t(unsigned int) 号码 -
@Piotrek 这取决于您正在为什么操作系统编程。但是,正如 R.. 所说,这可能不是您的程序中真正出错的原因。