Skip to content

Instantly share code, notes, and snippets.

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

What would you like to do?
How to sleep 0.5ms on Solaris
#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));
sigaddset(&set, SIGUSR1);
evp.sigev_notify = SIGEV_SIGNAL;
evp.sigev_signo = SIGUSR1;
if (timer_create(CLOCK_HIGHRES, &evp, &timer)) {
spec.it_interval = ts;
spec.it_value = ts;
gettimeofday(&start, NULL);
timer_settime(timer, 0, &spec, NULL);
sigwait(&set, &sig);
gettimeofday(&end, NULL);
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));

This comment has been minimized.

Copy link
Owner Author

wez commented May 24, 2011


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.