当我在下面运行我的代码时,我得到一个值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;
}
Run Code Online (Sandbox Code Playgroud)
返回的值clock()是类型clock_t(实现定义的算术类型).它表示"实现与程序使用的处理器时间的最佳近似值,因为实现定义的时代开始仅与程序调用相关"(N1570 7.27.2.1).
给定一个clock_t值,您可以通过乘以CLOCKS_PER_SEC一个实现定义的宏来确定它所代表的秒数<time.h>.POSIX需要CLOCKS_PER_SEC一百万,但它可能在不同的系统上具有不同的值.
请特别注意,那价值CLOCKS_PER_SEC就没有必要对应于实际精度clock()功能.
根据实现,clock()如果消耗的CPU时间量小于clock()函数的精度,则两次连续调用可能返回相同的值.在我测试的一个系统上,该clock()功能的分辨率为0.01秒; CPU可以在那段时间执行很多指令.
这是一个测试程序:
#include <stdio.h>
#include <time.h>
#include <limits.h>
int main(void) {
long count = 0;
clock_t c0 = clock(), c1;
while ((c1 = clock()) == c0) {
count ++;
}
printf("c0 = %ld, c1 = %ld, count = %ld\n",
(long)c0, (long)c1, count);
printf("clock_t is a %d-bit ", (int)sizeof (clock_t) * CHAR_BIT);
if ((clock_t)-1 > (clock_t)0) {
puts("unsigned integer type");
}
else if ((clock_t)1 / 2 == 0) {
puts("signed integer type");
}
else {
puts("floating-point type");
}
printf("CLOCKS_PER_SEC = %ld\n", (long)CLOCKS_PER_SEC);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在一个系统(Linux x86_64)上,输出为:
c0 = 831, c1 = 833, count = 0
clock_t is a 64-bit signed integer type
CLOCKS_PER_SEC = 1000000
Run Code Online (Sandbox Code Playgroud)
显然,在该系统上,clock()函数的实际分辨率为1或2微秒,并且两次连续调用以clock()返回不同的值.
在另一个系统(Solaris SPARC)上,输出为:
c0 = 0, c1 = 10000, count = 10447
clock_t is a 32-bit signed integer type
CLOCKS_PER_SEC = 1000000
Run Code Online (Sandbox Code Playgroud)
在该系统上,clock()函数的分辨率为0.01秒(10,000微秒),并且返回的值clock()在几千次迭代中没有变化.
还有(至少)还有一件需要注意的事情.在clock_t32位的系统上CLOCKS_PER_SEC == 1000000,该值可以在大约72分钟的CPU时间后回绕,这对于长时间运行的程序来说可能很重要.有关详细信息,请参阅系统文档.
| 归档时间: |
|
| 查看次数: |
4125 次 |
| 最近记录: |