Question

Could someone clear my following doubts regarding this code:

1) What is this clock() ? How does it work?

2)I have never seen ; after for statement when do i need to use these semicolons after for and will it loop though the only next line of code int tick= clock();?

3)Is he coverting tick to float by doing this: (float)tick ? Can i do this thing with every variable i initialize first as short, integer, long, long long and then change it to float by just doing float(variable_name)?

Thanks in advance

#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;
}
Was it helpful?

Solution

1) What is this clock() ? How does it work?

It reads the "CPU" clock of your program (how much time your program has taken so far). It is called RTC for Real Time Clock. The precision is very high, it should be close to one CPU cycle.

2) I have never seen ; after for statement when do i need to use these semicolons after for and will it loop though the only next line of code int tick= clock();?

No. The ';' means "loop by yourself." This is wrong though because such a loop can be optimized out if it does nothing. So the number of cycles that loop takes could drop to zero.

So "he" [hopes he] counts from 0 to 10 million.

3) Is he converting tick to float by doing this: (float)tick ? Can i do this thing with every variable i initialize first as short, integer, long, long long and then change it to float by just doing float(variable_name)?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top