关于c ++中的sleep命令

时间:2015-01-25 16:37:42

标签: c++ time sleep

我正在尝试使用sleep命令延迟程序。但是当我打印结果时,我没有看到延迟。我错过了什么。

#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;
}    

这是我的输出(我没有看到延迟有任何不同):

$ 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

1 个答案:

答案 0 :(得分:5)

您的问题出在您写的行上:

int usleep(useconds_t microseconds);

这是一个声明,而不是函数调用。将其更改为

usleep(microseconds);

你应该看到延迟。