Skip to content

Instantly share code, notes, and snippets.

@wez wez/msleep.c
Created May 24, 2011

Embed
What would you like to do?
How to sleep 0.5ms on Solaris
#define _POSIX_PTHREAD_SEMANTICS
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <stdio.h>
static double compute_time_diff(struct timeval start, struct timeval end)
{
double diff = end.tv_sec - start.tv_sec;
diff += (end.tv_usec - start.tv_usec) / 1000000.0;
return diff;
}
int main(int argc, char *argv[])
{
struct sigevent evp;
timer_t timer;
struct timeval start, end;
sigset_t set;
int sig;
struct itimerspec spec;
double diff;
struct timespec ts;
/* half a ms */
ts.tv_sec = 0;
ts.tv_nsec = 500000;
memset(&evp, 0, sizeof(evp));
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = SIGUSR1;
if (timer_create(CLOCK_HIGHRES, &evp, &timer)) {
perror("timer_create");
exit(1);
}
spec.it_interval = ts;
spec.it_value = ts;
gettimeofday(&start, NULL);
timer_settime(timer, 0, &spec, NULL);
sigwait(&set, &sig);
gettimeofday(&end, NULL);
timer_delete(timer);
printf("timer: diff: %f\n", compute_time_diff(start, end));
gettimeofday(&start, NULL);
nanosleep(&ts, NULL);
gettimeofday(&end, NULL);
printf("nanosleep: diff: %f\n", compute_time_diff(start, end));
exit(0);
}
@wez

This comment has been minimized.

Copy link
Owner Author

wez commented May 24, 2011

./msleep

timer: diff: 0.000575
nanosleep: diff: 0.009341

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.