gpt4 book ai didi

c - 每个字节的负周期? rdtsc C

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:23 28 4
gpt4 key购买 nike

我写了一些代码来测量每个字节的 CPU 周期。我得到负值 cpb 但不知道为什么......它告诉我 cpb = -0.855553 cycles/byte

我的伪代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

uint64_t rdtsc(){
unsigned int lo,hi;
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return ((uint64_t)hi << 32) | lo;
}

int main()
{
long double inputsSize = 1024;
long double counter = 1;

long double cpuCycleStart = rdtsc();

while(counter < 3s)
function(args);

long double cpuCycleEnd = rdtsc();

long double cpb = ((cpuCycleEnd - cpuCycleStart) / (counter * inputsSize));

printf("%Lf cycles/byte\n", cpb);

return 0;
}

编辑,改进代码,结果相同(负面):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

unsigned long rdtsc( void )
{
unsigned long lo, hi;
asm( "rdtsc" : "=a" (lo), "=d" (hi) );
return( lo );
}

int main()
{
long double counter;
long double inputsSize = 1024;
char *buff = createInput(inputsSize);

long double cpuCycleStart = rdtsc();
countDownTime(3.0);
for(counter=1; !secondsElapsed; counter++)
function(args);
long cpuCycleEnd = rdtsc();

long double cpb = ((cpuCycleEnd - cpuCycleStart) / (counter * inputsSize));

printf("%Lf cycles/byte\n", cpb);

return 0;
}

真是奇怪。编写测试代码:

printf("\n%lu cpuCycleEnd \n%lu cpuCycleStart \n", cpuCycleEnd, cpuCycleStart);
printf("\n%lu counter\n%lu inputsSize \n\n", counter, inputsSize);

long double cpb = (((long double)cpuCycleEnd - (long double)cpuCycleStart) / ((long double)counter * (long double)inputsSize));

printf("%Lf cycles/byte\n", cpb);

显示:

30534991 cpuCycleEnd 
1139165971 cpuCycleStart

1273029 counter
1024 inputsSize

-0.850450 cycles/byte

有什么想法吗?

最佳答案

您正在为一个目标进行编译,其中 unsigned long是 32 位。

你应该#include <stdint.h>并使用 uint64_t而不是 unsigned long .此外,您可能希望针对 unsigned long 的目标进行编译。是 64 位。

(注意:要打印 uint64_t#include <inttypes.h> 并使用 printf("%" PRIu64 "\n", value); 。)

关于c - 每个字节的负周期? rdtsc C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17970241/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com