关于 C++ 中的睡眠命令

regarding sleep command in c++

我正在尝试使用睡眠命令来延迟程序。但是当我打印结果时,我没有看到延迟。我是不是漏了什么。

#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

你的问题出在你写的那一行:

int usleep(useconds_t microseconds);

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

usleep(microseconds);

你应该会看到延迟。