1

I am trying to delay the program using sleep command. But when I print the results, I don't see the delay. Am I missing something .

#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <string.h>
#include <sys/time.h> // for time 
#include <unistd.h> // for microsecond sleep

using namespace std;

const std::string currentDateTime()
{
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}


int main(){

unsigned int microseconds = 10000000 ;

int min = 1;
int max = 10;
int randNum =0;
time_t t;

for(int i=0;i<5;i++)
{
randNum = rand()%(max-min + 1) + min;
std::cout << "At time "<< currentDateTime() << " Random portnumber is :  " << randNum <<"\n";
int usleep(useconds_t microseconds);
}
return 0;
}    

Here is my Output (I dont see any differnce in the delay):

$ g++ times.cc -lrt -o times
$ ./times 
At time 2015-01-25.16:34:15 Random portnumber is :  4
At time 2015-01-25.16:34:15 Random portnumber is :  7 
At time 2015-01-25.16:34:15 Random portnumber is :  8
At time 2015-01-25.16:34:15 Random portnumber is :  6
At time 2015-01-25.16:34:15 Random portnumber is :  4
user2532296
  • 828
  • 1
  • 10
  • 27
  • On a related note. I tried to improve the accuracy using high ranked suggestion given in http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds . But it constantly gives me only 0. Do you have any idea why so? – user2532296 Jan 25 '15 at 16:57

1 Answers1

5

Your problem is on the line where you write:

int usleep(useconds_t microseconds);

this is a declaration, not a function call. Change it to

usleep(microseconds);

and you should see the delay.

frasnian
  • 1,973
  • 1
  • 14
  • 24