0

有人可以清除我对此代码的以下疑虑:

1)这个时钟()是什么?它是如何工作的?

2)我从来没有见过;afterfor语句我什么时候需要使用这些分号for ,它是否会循环通过唯一的下一行代码int tick=clock(); ?

3)他是否通过这样做来将滴答声转换为浮动:(float)tick?我可以对我首先初始化为short、integer、long、long long的每个变量执行此操作,然后仅通过执行 float(variable_name) 将其更改为 float 吗?

提前致谢

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

int main()
{
int i;
for(i=0; i<10000000; i++);
int tick= clock();
printf("%f", (float)tick/ CLOCKS_PER_SEC);

return 0;
}
4

1 回答 1

1

1)这个时钟()是什么?它是如何工作的?

它读取您程序的“CPU”时钟(到目前为止您的程序花费了多少时间)。它被称为实时时钟的RTC。精度很高,应该接近一个CPU周期。

2)我从未见过;在 for 语句之后我什么时候需要在 for 之后使用这些分号,它是否会循环通过唯一的下一行代码 int tick=clock();?

不。';' 意思是“自己循环”。这是错误的,因为如果它什么都不做,这样的循环可以被优化掉。因此,循环所花费的周期数可能会降至零。

所以“他”[希望他]从0数到1000万。

3)他是否通过这样做将滴答声转换为浮动: (float)tick ?我可以对我首先初始化为 short、integer、long、long long 的每个变量执行此操作,然后仅通过执行 float(variable_name) 将其更改为 float 吗?

Yes. Three problems though:

a) he uses int for tick which is wrong, he should use clock_t.

b) clock_t is likely larger than 32 bits and a float cannot even accommodate 32 bit integers.

c) printf() anyway takes double so converting to float is not too good, since it will right afterward convert that float to a double.

So this would be better:

clock_t tick = clock();
printf("%f", (double)tick / CLOCKS_PER_SEC);

Now, this is good if you want to know the total time your program took to run. If you'd like to know how long a certain piece of code takes, you want to read clock() before and another time after your code, then the difference gives you the amount of time your code took to run.

于 2014-03-16T20:53:48.013 回答