我有一些代码试图确定代码块的执行时间。
#include <time.h>
#include <stdio.h>
int main()
{
clock_t start_t, end_t, total_t;
int i;
start_t = clock(); //clock start
printf("Starting of the program, start_t = %ld\n", start_t);
printf("Going to scan a big loop, start_t = %ld\n", start_t);
for(i=0; i< 10000000; i++) //trying to determine execution time of this block
{
}
end_t = clock(); //clock stopped
printf("End of the big loop, end_t = %ld\n", end_t);
total_t = (long int)(end_t - start_t);
printf("Total time taken by CPU: %lu\n", total_t );
return(0);
}
我机器上代码片段的输出是
Starting of the program, start_t = 8965
Going to scan a big loop, start_t = 8965
End of the big loop, end_t = 27259
Total time taken by CPU: 18294
因此,如果我的 CPU 以 21 MHz 运行并假设这是唯一执行的操作,则每个机器周期大约等于 47 纳秒,因此 (18294 * 47) = 859818 纳秒。
这会是我代码中 for 循环的执行时间吗?我在这里做了一些不正确的假设吗?