Interval Timer in c

All you will need is a c compiler and your set. Here we go :P

#include <time.h>

This header enables the use of many functions to do with time, one of which is the clock_t function. We’ll delve into the clock_t function a bit later.

#include <stdio.h>
The <stdio.h> header lets use use about 60 functions like “printf”, “getchar()”, “fopen”, “system()” etc..

int main ( void )
This just tells the compiler that its the start of the main body of the program.

clock_t start, stop;
The clock_t function holds the data returned by the “clock” function. (mentioned later)

“start, stop;” – Declaring start and stop are part of this function. Notice that start is first and stop is last, it’s also telling the compiler that “start” means start the clock and “stop” means stop the clock. You could have “cat” and “dog”.

start = clock();
In c there is also a function called “clock” which returns the number of clock ticks of elapsed processor time, and this is telling the “clock” function to start and the “clock_t” function will hold the clock ticks.

printf ( “Timing……n” );
This just prints “Timing……” in the console. The n tell it to goto a new line.

getchar();
Now, this is telling the program to continue timing till the “Enter” has been pressed.
in its place you could have a while statement like:

int c;
while(c <= 1000)
c++;

So it times the time it had took to count to 1000.

end = clock();

This is telling the “clock” to stop returning the clock ticks, hence “clock_t” will stop recording any.

printf ( “The time of the interval was: %f secondsn”,
(double)( stop – start ) /(double)CLOCKS_PER_SEC );

The above prints “The time of the interval was: %f seconds” and the lower is just a calculation that turn the CLOCK_PER_SEC into eg. 6.1234 seconds ie. a real number

system(“pause”);
It’s so that the program pauses so you can read the results

return 0;
Exits the program.

The full script:

#include <stdio.h>
#include <time.h>
int main ( void )
{
clock_t start, stop;
start = clock();
printf ( "Timing......n" );
getchar();
stop = clock();
printf ( "The interval was: %f secondsn",
(double)( y - x ) / (double)CLOCKS_PER_SEC );
system("pause");
return 0;
}

Related posts:

  1. Swapping with no temporary variable
  2. [MobileApps]The Key Lock Clock for Symbian OS
  3. [XP Hack]Disabling USB Ports
  4. Secure PHP Programming!
  5. Make your own web browser

Tags: ,

3 Responses to “Interval Timer in c”

  1. Sudhanshu 16. Apr, 2007 at 10:24 am #

    I think that to create a more accurate timer, you need use the ’select’ function.

  2. master 16. Jun, 2009 at 8:06 am #

    Really Good Example and it’s so simple to understand

  3. master 16. Jun, 2009 at 8:07 am #

    Please replace y – x with stop – start

Leave a Reply