Skip to content

Instantly share code, notes, and snippets.

@heechul
Created April 25, 2012 14:15
Show Gist options
  • Save heechul/2490000 to your computer and use it in GitHub Desktop.
Save heechul/2490000 to your computer and use it in GitHub Desktop.
timer resolution check user application
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#define USECREQ 250
#define LOOPS   1000
static int g_req_ns = USECREQ * 1000;
static void event_handler (int signum)
{
        static unsigned long cnt = 0;
        static struct timespec tsFirst;
        if (cnt == 0) {
                clock_gettime(CLOCK_REALTIME, &tsFirst);
        }
        cnt ++;
        if (cnt >= LOOPS) {
                struct timespec tsNow;
                long ndiff;
                clock_gettime(CLOCK_REALTIME, &tsNow);
                ndiff = (tsNow.tv_sec - tsFirst.tv_sec) * 1000000 +
                        (tsNow.tv_nsec - tsFirst.tv_nsec);
                double delta = (double)(ndiff/cnt)/1000000000;
                int hz = (unsigned)(1.0/delta);
                printf ("kernel timer interrupt frequency is approx. %d Hz", hz);
                if (hz >= (int) (1.0/((double)(g_req_ns)/1000000000))) {
                        printf (" or higher");
                }
                printf ("\n");
                exit (0);
        }
}
 
int main (int argc, char **argv)
{
        timer_t tid;
        struct itimerspec its;
        struct sigaction sa;
 
        if (argc >= 2)
                g_req_ns = atoi(argv[1]);
 
        printf("requsted hz = %d\n", 1000000000/g_req_ns);
        memset (&sa, 0, sizeof (sa));
        sa.sa_handler = &event_handler;
        sigaction (SIGALRM, &sa, NULL);
 
        if ( timer_create(CLOCK_REALTIME, NULL, &tid) < 0) {
                perror("create failed");
                exit(1);
        }
 
        its.it_value.tv_sec = 1;
        its.it_value.tv_nsec = 0;
        its.it_interval.tv_sec = 0;
        its.it_interval.tv_nsec = g_req_ns;
 
        if (timer_settime(tid, 0, &its, NULL) < 0) {
                perror("failed to set timer");
                exit(2);
        }
        while (1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment