As part of getting a workload with a varying response time, I wanted the server to wait for a short amount of time between processing requests. This was pretty easy, but there were a couple of challenges
The code
#ifndef __timespec_struct
#define __timespec_struct 1
struct timespec
{
time_t tv_sec;
long tv_nsec;
};
#endif
struct timespec randomWait;
#undef RAND_MAX
#define RAND_MAX 100
j = RAND_MAX;
int myrand = rand();
printf("Random number %i %i\n",myrand,j);
randomWait.tv_sec = 0 ;
randomWait.tv_nsec = myrand * 1000000;
nanosleep(randomWait, NULL); // if specified
Define timespec structure
The documentation for nanosleep gave some example code. When I used it, I got a compile error
"struct timespec" is undefined.
I found it easier to define the timespec structure myself.
Set the upper limit for the random number.
You do not pass the upper limit to the rand() function. The value is taken from the #DEFINE RAN_MAX. (A strange way of doing it). The default upper limit is 32767.
To set your own limit, you need to #undef, then #define with the new value.
Setting the random time
The timespec structure has the value in seconds and nanoseconds. Because I wanted a random wait in milliseconds, I used random_value * 1000000 to convert to nano seconds.