Random header image... Refresh for more!
Visitors

free invisible counter
Partner sites
http://consigliere.sk
--------------------------- led-svetla.sk
---------------------------
multi.xeres.cz

High resolution timers was implemented in kernel 2.6.16 and provide better resolution like 1 jiffy. Code was created by Ingo Molnar and Thomas Greixner. Implementation should provide high precision timers (with granularity ~1us) for userspace applications.Simple code below  check what is precise of resolution of high resolution timers implemented in kernel. It is also example program how to create periodic timer with high resolution in userspace.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <signal.h>
#include <unistd.h>

#define NSEC_PER_SEC 1000000000L

#define timerdiff(a,b) ((float)((a)->tv_sec - (b)->tv_sec) + \
((float)((a)->tv_nsec - (b)->tv_nsec))/NSEC_PER_SEC)

static struct timespec prev = {.tv_sec=0,.tv_nsec=0};
static int count = 5;

void handler( signo )
{
struct timespec now;

clock_gettime(CLOCK_MONOTONIC, &now);
printf("[%d]Diff time:%lf\n", count, timerdiff(&now, &prev));
prev = now;
count --;
}

int main(int argc, char *argv[])
{
int i = 0;
timer_t t_id;

struct itimerspec tim_spec = {.it_interval= {.tv_sec=1,.tv_nsec=10000},
.it_value = {.tv_sec=1,.tv_nsec=10000}};

struct sigaction act;
sigset_t set;

sigemptyset( &set );
sigaddset( &set, SIGALRM );

act.sa_flags = 0;
act.sa_mask = set;
act.sa_handler = &handler;

sigaction( SIGALRM, &act, NULL );

if (timer_create(CLOCK_MONOTONIC, NULL, &t_id))
perror("timer_create");

if (timer_settime(t_id, 0, &tim_spec, NULL))
perror("timer_settime");

clock_gettime(CLOCK_MONOTONIC, &prev);

for (; ; )
{
if(count == 0)
break;
}

return 0;
}

Program explanation:

- define sigaction for signal SIGALRM which is received if timer expired

- create timer (timer is not started)

- set timer (this function start timer)

- wait for 5 periods and then exit

In output you should see values for 5 period of timer. Timer is set to 1 seconds and 1us interval.

Note: for compiling please add to CFLAGS option: -lrt (realtime library).

Source for download: test_timerc

Marek

Leave a Reply