Calculate program execute time / time elapsed in C

Here i shared a simple method to calculate program execute time or time elapsed in C

/*calculate program execute time */
#include 
#include 

int main(int argc, char *argv[]) {
   time_t start, stop;
   clock_t ticks; long count;

   time(&start);
   // Do stuff
   int i=0;

   while(i<50000)
   {
	printf("Work work %d\n", i);
        i++;
        ticks = clock();

   }

   time(&stop);
   
   printf("Used %0.2f seconds of CPU time. \n", (double)ticks/CLOCKS_PER_SEC);
   printf("Finished in about %.0f seconds. \n", difftime(stop, start));
   return 0;
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
7 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
8 Comment authors
d jamesRushikesh Tadeshtiiit tarun1625jeni Recent comment authors
newest oldest most voted
d james
Guest
d james

helped me so much

Rushikesh Tade
Guest
Rushikesh Tade

Thanks.

sht
Guest
sht

hi sir.
what is answer this qustion:
calculating order (an^2+b+c)

iiit tarun1625
Guest
iiit tarun1625

Thanks but
please explain that parameters in program

devi
Guest
devi

hello sir,
my name is devi from india. i cant understand the concept behind it.
can u please explain me the concept?

flint
Guest
flint

thanks a lot. :D

haba
Guest
haba

nice xD, (in romanian: fac laba acuma :X:X)

jeni
Guest
jeni

i want elapsed time with milliseconds in c++ or c.

example :
Start time = 01hr:45min:20sec.500ms
End time = 01hr:45min:20sec.1500ms

(1500ms-500ms =1000ms=1sec)

elapsed time = 0hr:0min:1sec.0ms

Please help