Interval Timer in c


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

#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.

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)

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 seconds\n”,
(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

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" );
stop = clock();
printf ( "The interval was: %f seconds\n",
(double)( y - x ) / (double)CLOCKS_PER_SEC );
return 0;

3 Responses to “Interval Timer in c”

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

  2. 2 master

    Really Good Example and it’s so simple to understand

  3. 3 master

    Please replace y – x with stop – start

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: