我正在尝试使用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
最佳答案
您的问题出在您写的那行:
int usleep(useconds_t microseconds);
这是一个声明,而不是函数调用。更改为
usleep(microseconds);
您应该会看到延迟。
关于c++ - 关于C++中的sleep命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28138730/