【发布时间】:2015-03-04 00:27:22
【问题描述】:
当我在下面运行我的代码时,我得到了一个值 0,有几次我确实得到了 intAddition 的值。我尝试了很多我在网上找到的建议,但还没有成功。我的同学向我展示了他的做法,这与我的非常相似。他从他的程序中获得了 1 到 3 的小值。
感谢您的帮助!
#include <iostream>
#include <time.h>
#include <stdio.h>
clock_t start, end;
void intAddition(int a, int b){
start = clock();
a + b;
end = clock();
printf("CPU cycles to execute integer addition operation: %d\n", end-start);
}
void intMult(int a, int b){
start = clock();
a * b;
end = clock();
printf("CPU cycles to execute integer multiplication operation: %d\n", end-start);
}
void floatAddition(float a, float b){
start = clock();
a + b;
end = clock();
printf("CPU cycles to execute float addition operation: %d\n", end-start);
}
void floatMult(float a, float b){
start = clock();
a * b;
end = clock();
printf("CPU cycles to execute float multiplication operation: %d\n", end-start);
}
int main()
{
int a,b;
float c,d;
a = 3, b = 6;
c = 3.7534, d = 6.85464;
intAddition(a,b);
intMult(a,b);
floatAddition(c,d);
floatMult(c,d);
return 0;
}
【问题讨论】:
-
clock以相当粗略的方式返回 CPU 时间(通常以 1-100 毫秒为增量)。不是 CPU 的时钟周期。所以,是的,我希望每次都为零。 -
你应该循环操作被计时很多次。但是注意,如果你只写
a+b,编译器可能会优化掉它,因为它没有任何效果。 -
我刚刚尝试循环操作,但我仍然得到 0。
-
@Ugluk 多少次迭代?从100万开始。至少。要获得真实的 CPU 周期数,您需要类似
rdtsc,而不是clock。 -
不要假设
clock_t值可以用%d打印。clock_t是实现定义的算术类型。您可以将其转换为已知类型,例如printf("%ld\n", (long)(end - start));