Thursday, 20 March 2014

 Have you ever thought about what if you could know the time taken by your code to run. That's what todays post is all about.

Knowing the speed of your program or algorithm is very important. Because that's the only way to make it better and faster. Today i am going to show you how you can calculate the running time of your program.
     For doing this you first need to include the header file "time.h". Then declare two variables of "time_t" type i.e "time1" and "time2". Save the current time in variable time1(time (&time1);) then at the end of the program again save the value of current time this time in "time2"(time (&time);). Then call the method "difftime(time2,time1);"  like this. And this will return you the time taken in seconds.
      Similarly if you want to calculate the time for a specific method save the current time before and after the method and call the function "difftime()".

#include <stdio.h> #include <time.h> #include<conio.h> #include<iostream.h> void main (void) { clrscr(); int sum,a,b; time_t time1,time2; double dif_sec; time (&time1); cout << "Enter the value of a :"<<endl; cin >> a; cout << "Enter the value of b :"<<endl; cin >> b; sum = a + b; time (&time2); dif_sec = difftime (time2,time1); cout << "\nThe sum is : " << sum<<endl; cout << "\nIt took you " << dif_sec << " seconds to enter the numbers and calculate the sum"<<endl; cout << "Press Any key to Continue....."; getch(); }

Output :


If you like my post Comment below and subscribe for more :) !!!

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!