02 November 2009

Timers

Ok well I decided to take this in a little different direction. I am going to start putting small bits of code up here and piece them together into different things. That way you can learn and I can experiment. So if you are as excited as I am about programming then whip out your compiler and lets get started.
The first thing I will go over is how to create a simple timer which you can use to trigger things. What things? Anything you want really. In my example it will put a line out to the console after a certain amount of milliseconds.
By the way, 1000 milliseconds is equal to 1 second. So 10000 milliseconds would be equal to 10 seconds. It seems complicated but lets take a look.
One thing you should also consider is that time is relative when dealing with different operating systems. A tick is the smallest resolution of time that the CPU your dealing with can process. (I generally think of a tick as 1 millisecond) In my example I am using a long variable named sc_timer. It will capture the current time by using getticks(); function. To get the timer to trigger, you subtract sc_timer from getticks(). The result is how much time has passed since you last updated the sc_timer variable. Pretty dang cool. You can use an if statement to compare if the elapsed time is greater than a certain amount of milliseconds. In my example I used 10000 milliseconds (10 seconds).

I created a console application in Code::Blocks and modified it... main.cpp:

#include <iostream>
#include "sc_getticks.h"
using namespace std;
long sc_timer;
int main()
{
sc_timer=getticks();
while(1)
{
if( (getticks() - sc_timer) > 10000)
{
sc_timer=getticks();
cout << sc_timer << "\n";
}
}
return 0;
}



Next I created a new file and called it sc_getticks.cpp

#ifdef _WIN32
#include <windows.h>
#endif
#include "sc_getticks.h"
long getticks(void)
{
#ifdef _WIN32
return GetTickCount();
#else
long curtime; struct timeval tp; struct timezone tzp; static long secbase;
gettimeofday(&tp,&tzp); if(!secbase) { secbase = tp.tv_sec; return tp.tv_usec/1000; }
curtime = (tp.tv_sec - secbase)*1000 + tp.tv_usec/1000; return curtime;
#endif
}
You can see that I put in some preprocesser directives. Don't worry about that for now. All you want to concentrate on is that this function will return the current tick count. (Note: if you are just using Windows systems you can replace getticks(); function and file and just use GetTickCount(); )

One more file... (its a small one) sc_getticks.h
extern "C" long getticks(void);
Now when you compile all this together you should get a console application that spits out the current tick count once every 10 seconds.

There you have it, a relatively painless timer. What you do with it is up to you. I will build on this example so stay tuned!

Download files for this project

No comments:

Post a Comment