c - Difference between clock_t and time_t or time(NULL) and clock() -



c - Difference between clock_t and time_t or time(NULL) and clock() -

i write c programme print integer value on every 1 sec exercise,this programme print integer after wait 1 sec before printing next integer programme take 5 seconds finish execution.i using clock_t , time() timer , works when utilize clock_t , clock timer doesn't work.

as know time_t , time() absolute time , using seconds elapsed since 1970.while clock_t , clock() utilize time since programme run.

this first code using time_t , time(null)

#include <stdio.h> #include <time.h> int main (void) { int i; int sec=1; time_t start,end; start=time(null); for(i=1;i<=5;i++){ time_t wait=sec+time(null); while(time(null) < wait) {} printf("%d\n",i); } end=time(null); printf("program take %d second\n",(unsigned int)difftime(end,start)); homecoming 0; }

and result when programme run:

1 2 3 4 5 programme take 5 sec

execution of programme print integers on every 1 sec or wait 1 sec before printing next integer

this sec programme using clock_t , clock()

#include <stdio.h> #include <time.h> int main (void) { int sec=1; int i; clock_t start,end; start=clock(); for(i=1;i<=5;i++){ clock_t wait=sec*clocks_per_sec; while(clock ()<wait){} printf("%d\n",i); } end=clock(); printf("the programme take %lf second\n",(double)(end-start)/clocks_per_sec); homecoming 0; }

this result of sec programme using clock_t , clock()

1 2 3 4 5 programme take 0.998901 sec

and after execution doesn't print every 1 sec first wait 1 sec , print of integers instead of wait 1 sec before print next integer.

please explain happen sec programme , difference between time() , clock() function?

in first program, this:

time_t wait=sec+time(null);

causes wait alter every time through loop, becoming 1 sec later current time (on systems time_t measured in seconds, @ least, common, not required).

in sec program, this:

clock_t wait=sec*clocks_per_sec;

has same value every time execute it, since value of sec never changes. in sec program, loop wait on first iteration until 1 sec past programme start, , on subsequent iterations never wait again, because more 1 sec have passed since programme start , clock() < wait never 1 time again true.

in short, 2 loops aren't close doing same thing, there's no reason you'd expect them behave in similar ways. if changed:

clock_t wait=sec*clocks_per_sec;

to:

clock_t wait = * clocks_per_sec;

then might closer you're expecting.

c time.h

Comments

Popular posts from this blog

java - Bypassing "final local variable defined in an enclosing type" -

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -