How does one create a timer in C?
I want a piece of code to continuously fetch data from a gps parsers output.
Are there good libraries for this or should it be self written?
Simplest method available:
#include <pthread.h>
void *do_smth_periodically(void *data)
{
int interval = *(int *)data;
for (;;) {
do_smth();
usleep(interval);
}
}
int main()
{
pthread_t thread;
int interval = 5000;
pthread_create(&thread, NULL, do_smth_periodically, &interval)
...
}
On POSIX systems you can create (and catch) an alarm. Alarm is simple but set in seconds. If you need finer resolution than seconds then use setitimer.
struct itimerval tv;
tv.it_interval.tv_sec = 0;
tv.it_interval.tv_usec = 100000; // when timer expires, reset to 100ms
tv.it_value.tv_sec = 0;
tv.it_value.tv_usec = 100000; // 100 ms == 100000 us
setitimer(ITIMER_REAL, &tv, NULL);
And catch the timer on a regular interval by setting sigaction.
One doesn't "create a timer in C". There is nothing about timing or scheduling in the C standard, so how that is accomplished is left up to the Operating System.
This is probably a reasonable question for a C noob, as many languages do support things like this. Ada does, and I believe the next version of C++ will probably do so (Boost has support for it now). I'm pretty sure Java can do it too.
On linux, probably the best way would be to use pthreads. In particular, you need to call pthread_create() and pass it the address of your routine, which presumably contains a loop with a sleep() (or usleep()) call at the bottom.
Note that if you want to do something that approximates real-time scheduling, just doing a dumb usleep() isn't good enough because it won't account for the execution time of the loop itself. For those applications you will need to set up a periodic timer and wait on that.
SDL provides a cross platform timer in C.
http://www.libsdl.org/cgi/docwiki.cgi/SDL_AddTimer
If your using Windows, you can use SetTimer,else you can build a timer out of timeGetTime and _beginthreadex along with a queue of timers with callbacks
The question about a timer is quite unspecific, though there are two functions that come to my mind that will help you:
sleep() This function will cause execution to stop for a specified number of seconds. You can also use usleep and nanosleep if you want to specify the sleeptime more exactly
gettimeofday() Using this function you are able to stop between to timesteps.
See manpages for further explanation :)
If the gps data is coming from some hardware device, like over a serial port, then one thing that you may consider is changing the architecture around so that the parser kicks off the code that you are trying to run when more data is available.
It could do this through a callback function or it could send an event - the actual implementation would depend on what you have available.
Related
I want to implement a delay function using null loops. But the amount of time needed to complete a loop once is compiler and machine dependant. I want my program to determine the time on its own and delay the program for the specified amount of time. Can anyone give me any idea how to do this?
N. B. There is a function named delay() which suspends the system for the specified milliseconds. Is it possible to suspend the system without using this function?
First of all, you should never sit in a loop doing nothing. Not only does it waste energy (as it keeps your CPU 100% busy counting your loop counter) -- in a multitasking system it also decreases the whole system performance, because your process is getting time slices all the time as it appears to be doing something.
Next point is ... I don't know of any delay() function. This is not standard C. In fact, until C11, there was no standard at all for things like this.
POSIX to the rescue, there is usleep(3) (deprecated) and nanosleep(2). If you're on a POSIX-compliant system, you'll be fine with those. They block (means, the scheduler of your OS knows they have nothing to do and schedules them only after the end of the call), so you don't waste CPU power.
If you're on windows, for a direct delay in code, you only have Sleep(). Note that THIS function takes milliseconds, but has normally only a precision around 15ms. Often good enough, but not always. If you need better precision on windows, you can request more timer interrupts using timeBeginPeriod() ... timeBeginPeriod(1); will request a timer interrupt each millisecond. Don't forget calling timeEndPeriod() with the same value as soon as you don't need the precision any more, because more timer interrupts come with a cost: they keep the system busy, thus wasting more energy.
I had a somewhat similar problem developing a little game recently, I needed constant ticks in 10ms intervals, this is what I came up with for POSIX-compliant systems and for windows. The ticker_wait() function in this code just suspends until the next tick, maybe this is helpful if your original intent was some timing issue.
Unless you're on a real-time operating system, anything you program yourself directly is not going to be accurate. You need to use a system function to sleep for some amount of time like usleep in Linux or Sleep in Windows.
Because the operating system could interrupt the process sooner or later than the exact time expected, you should get the system time before and after you sleep to determine how long you actually slept for.
Edit:
On Linux, you can get the current system time with gettimeofday, which has microsecond resolution (whether the actual clock is that accurate is a different story). On Windows, you can do something similar with GetSystemTimeAsFileTime:
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
const unsigned __int64 epoch_diff = 11644473600000000;
unsigned __int64 tmp;
FILETIME t;
if (tv) {
GetSystemTimeAsFileTime(&t);
tmp = 0;
tmp |= t.dwHighDateTime;
tmp <<= 32;
tmp |= t.dwLowDateTime;
tmp /= 10;
tmp -= epoch_diff;
tv->tv_sec = (long)(tmp / 1000000);
tv->tv_usec = (long)(tmp % 1000000);
}
return 0;
}
You could do something like find the exact time it is at a point in time and then keep it in a while loop which rechecks the time until it gets to whatever the time you want. Then it just breaks out and continue executing the rest of your program. I'm not sure if I see much of a benefit in looping rather than just using the delay function though.
I want to write a task that does some polling on some IOs. Now, I need it to not block the cpu but to check the IOs every 1 microsecond or so.
I'm a relative VxWorks newbie and just realized that inserting a usleep(1); into my polling loop probably won't do what I need it to do. How do I best go about this?
I have figured out that sysClkRateGet() returns 60 which isn't good enough for me. I need to poll and react fast but can't block the other things that are going on in the CPU, so I guess taskDelay() won't do it for me... is there anything else that allows for a shorter downtime of my task (than 1/60 seconds)?
edit
I think I've figured out that it's much smarter to have a timer kicking in every 1us that executes my short polling function.
i triggered the timer like this:
timer_t polltimerID;
struct itimerspec poll_time;
poll_time.it_value.tv_sec = 0;
poll_time.it_value.tv_nsec= 1000;
poll_time.it_interval.tv_sec = 0;
poll_time.it_interval.tv_nsec= 1000; // execute it every 1us
if(timer_create (CLOCK_REALTIME, NULL, &polltimerID))
printf("problem in timer_create(): %s",strerror(errno));
if(timer_connect (polltimerID,MyPollFunction,0))
printf("problem in timer_connect(): %s",strerror(errno));
if(timer_settime (polltimerID, 0, &poll_time, NULL))
printf("problem in timer_settime(): %s",strerror(errno));
But I'm not exactly sure yet, what the priority of the timer is and if (and how) it is able to preempt a current task, anyone?
The posix timer won't do what you want as it's driven off the system clock (which as you pointed out is at 60Hz).
There is no "built-in" OS function that will give you a 100KHz timer.
You will have to find some unused hardware timer on your board (CPU reference manual is useful)
You will have to configure the timer registers for you 100KHz (again Ref. Manual is good)
You will have to hook up the timer interrupt line to your function: intConnect (vector, fn, arg)
The VxWorks Kernel programmers manual has information about writing Interrupt Service Routines.
How do I execute a function once every 1000 milliseconds using alarm() or sleep? I want the program to do something else if the function does not execute or complete in 1000 milliseconds.
EDIT: added Pseudocode
while(true) {
alarm(1000);
execute function;
sleep(1000);
alarm(0);
}
Now if alarm(1000) signals SIGALRM is this where I could call the other function?
I'm new to this sort of stuff so not even sure if I am using it right.
How crisp is the requirement, ie, how much jitter can you tolerate?
What version of UNIX?
Basically, if this is a hard deadline -- it sounds like one -- you're going to need to do some special stuff, because basic UNIX isn't really a hard-real-time system.
Let's assume for the moment that you mean Linux. You'll want to
use nice(2) to raise the process priority
use a fine-grained timer, as with ualarm(3)
That will probably do. If you need finer grained, or more predictable, timing, then you probably need to write a kernel extension to it can be driven with a kernel timer. (Solaris has some improved support for hard-real-time, but it's still not really a hard real-time system.)
Life will get considerably easier if you can use a real-time Linux or UNIX. Here's a list of some options. Here's an article you might find usefui.
Update
You should also look at nanosleep(2) or setitimer(2). Notice that all of these say the interval is at least the one in the argument. If you have a hard deadline, you need to wait for somewhat less than the actual interval and then figure out what to do with any change on your thousand millisecs.
I have used this function on Linux to "sleep" in milliseconds:
void Sleep(unsigned int milliSeconds)
{
struct timespec req = {0};
time_t seconds = (int) (milliSeconds / 1000);
milliSeconds = milliSeconds - (seconds * 1000);
req.tv_sec = seconds;
req.tv_nsec = milliSeconds * 1000000L;
while (nanosleep(&req, &req) == -1)
continue;
}
while (1) {
sleep(1);
/* Act */
}
If you need tighter delays, the normal way to do it is to call select() with no fds and a low timeout.
How can I block my thread (maybe process) for nanoseconds or maybe for a milliseconds (at least) period?
Please note that I can't use sleep, because the argument to sleep is always in seconds.
nanosleep or clock_nanosleep is the function you should be using (the latter allows you to specify absolute time rather than relative time, and use the monotonic clock or other clocks rather than just the realtime clock, which might run backwards if an operator resets it).
Be aware however that you'll rarely get better than several microseconds in terms of the resolution, and it always rounds up the duration of sleep, rather than rounding down. (Rounding down would generally be impossible anyway since, on most machines, entering and exiting kernelspace takes more than a microsecond.)
Also, if possible I would suggest using a call that blocks waiting for an event rather than sleeping for tiny intervals then polling. For instance, pthread_cond_wait, pthread_cond_timedwait, sem_wait, sem_timedwait, select, read, etc. depending on what task your thread is performing and how it synchronizes with other threads and/or communicates with the outside world.
One relatively portable way is to use select() or pselect() with no file descriptors:
void sleep(unsigned long nsec) {
struct timespec delay = { nsec / 1000000000, nsec % 1000000000 };
pselect(0, NULL, NULL, NULL, &delay, NULL);
}
Try usleep(). Yes this wouldn't give you nanosecond precision but microseconds will work => miliseconds too.
Using any variant of sleep for pthreads, the behaviour is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads. Hence a solution is required which the pthread library can handle rather than the kernel.
A safer and cleaner solution to use is the pthread_cond_timedwait...
pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;
void mywait(int timeInSec)
{
struct timespec timeToWait;
struct timeval now;
int rt;
gettimeofday(&now,NULL);
timeToWait.tv_sec = now.tv_sec + timeInSec;
timeToWait.tv_nsec = now.tv_usec*1000;
pthread_mutex_lock(&fakeMutex);
rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
pthread_mutex_unlock(&fakeMutex);
printf("\nDone\n");
}
void* fun(void* arg)
{
printf("\nIn thread\n");
mywait(5);
}
int main()
{
pthread_t thread;
void *ret;
pthread_create(&thread, NULL, fun, NULL);
pthread_join(thread,&ret);
}
For pthread_cond_timedwait , you need to specify how much time to wait from current time.
Now by the use of the function mywait() only the thread calling it will sleep and not the other pthreads.
nanosleep allows you to specify the accuracy of the sleep down to nano-seconds. However the actual resolution of your sleep is likely to be much larger due to the kernel/CPU limitations.
Accurate nano-second resolution is going to be impossible on a general Linux OS, due to the fact that generally Linux distributions aren't (hard) real-time OSes. If you really need that fined grained control over timing, consider using such an operating system.
Wikipedia has a list of some real-time operating systems here: http://en.wikipedia.org/wiki/RTOS (note that it doesn't say if they are soft or hard real time, so you'll have to do some research).
On an embedded system with access to multiple hardware timers, create a high-speed clock for your nanosecond or microsecond waits. Create a macro to enable and disable it, and handle your high-resolution processing in the timer interrupt service routine.
If wasting power and busywaiting is not an issue, perform some no-op instructions - but verify that the compiler does not optimize your no-ups out. Try using volatile types.
gcc 4.4.3
vc++ 2008
I would like to make a timer application would be portable on windows and linux. However, would be suffice to start with.
My idea is to start a timer and set it for a specified number of seconds. When the time expires call a callback function.
Is that the best way to do this?
Many thanks,
There are many ways to do a timer. It is not hard but you need to think exactly what you want. If you want to call a callback, you usually use a thread that sleep until your delay is elapsed, before calling your callback. If you don't want to use a thread, you can call periodically a checker function that compute the time delta.
You api will be a function taking the delay and a function pointer plus the callback parameters. It will launch a thread that will sleep for the delay, then call the callback with the given parameters.
Check general purpose libraries, they usually have timers implemented (gtk+ glib, boost::timer I think).
my2c
Edit:
For the portability part, you have of course to write two versions of your timer function. If you use thread that means it is better to use a lib. As libs give you timers ... Use a lib :)
Windows and linux do timers differently. I suggest that you encapsulate the timing functionality into a class. You'll have to write the class twice (once for each platform) but then the rest of the program can be the same.
Alternatively you can use a toolkit where somebody else gas already done it for you. e.g. QT or Boost.
I have worked with several such timers in both C and C++. For C GTK example on the following url may be helpful http://zetcode.com/tutorials/gtktutorial/gtkevents/. In C++ I used glib timer https://developer.gnome.org/glibmm/2.34/classGlib_1_1SignalTimeout.html (although it is not precise). I also work with libev (which uses epoll() on Linux and select() on Windows) for better precision timer. For C, I present an example below
//This program is demo for using pthreads with libev.
//Try using Timeout values as large as 1.0 and as small as 0.000001
//and notice the difference in the output
//(c) 2013 enthusiasticgeek for stack overflow
//Free to distribute and improve the code. Leave credits intact
//On Ubuntu (assuming libev is installed) compile with the command - gcc -g test.c -o test -lev
#include <ev.h>
#include <stdio.h> // for printf
#include <stdlib.h>
double timeout = 1.0; //seconds
ev_timer timeout_watcher;
int timeout_count = 0;
static void timeout_cb (EV_P_ ev_timer *w, int revents) // Timer callback function
{
++timeout_count;
printf("%d\n", timeout_count);
w->repeat = timeout;
ev_timer_again(loop, &timeout_watcher); //Start the timer again.
}
int main (int argc, char** argv)
{
struct ev_loop *loop = EV_DEFAULT; //or ev_default_loop (0);
ev_timer_init (&timeout_watcher, timeout_cb, timeout, 0.); // Non repeating timer. The timer starts repeating in the timeout callback function
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_loop(loop, 0);
return 0;
}
For more docs on libev view http://doc.dvgu.ru/devel/ev.html