Learn C By Example
Version: 1.0.0
Date: 22nd February 2008
Timing Your Code
Sometimes you want to time how long your code is taking to perform it's task. Here is an example showing how you can do just that.
/* ===============
* Timer Program
* ===============
* Purpose: Program to illustrate how you can use C to find out how
* long it takes your program code to execute.
*
* Notes: At this time (21st Feb 2008), I haven't tried compiling
* and testing this program snippet... but hopefully you will
* find that it works without modification. I'll try to
* test it myself in due course. In the mean time, feel
* free to drop me a line if you have any comment about this
* code.
*
* Author: Eddie Meyer
* Date: 21 FEB 2008
*/
#include <stdio.h>
#include <time.h>
int main(void)
{
clock_t start_time;
clock_t end_time;
clock_t elapsed_time;
double elapsed_time_seconds;
/* Record the start time */
start_time = clock();
/* Place the code you wish to time here */
/* Make a note of the end time */
end_time = clock();
/* Calculate the elapsed time in seconds */
elapsed_time = end_time - start_time;
elapsed_time_seconds = elapsed_time / (double) CLOCKS_PER_SEC;
/* Display the results */
printf("Your code took %.2f seconds to execute.",elapsed_time_seconds);
return 0;
}
Reference Material:
- http://www.cplusplus.com/reference/clibrary/ctime - Information on the ctime library.
Copyright © 2008 Eddie Meyer
