Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;函数在windows中完美运行,而不是linux?_C++_Linux - Fatal编程技术网

C++ C++;函数在windows中完美运行,而不是linux?

C++ C++;函数在windows中完美运行,而不是linux?,c++,linux,C++,Linux,我试图编写一个简单的C++函数睡眠(int毫秒)< /> >,它将为用户指定的毫秒睡眠程序。 这是我的密码: #include <iostream> #include <time.h> using namespace std; void sleep(unsigned int mseconds) { clock_t goal = mseconds + clock(); while (goal > clock()); } int main() {

我试图编写一个简单的C++函数<代码>睡眠(int毫秒)< /> >,它将为用户指定的毫秒睡眠程序。 这是我的密码:

#include <iostream>
#include <time.h>

using namespace std;

void sleep(unsigned int mseconds) {
    clock_t goal = mseconds + clock();
    while (goal > clock());
}

int main() {
    cout << "Hello World !" << endl;
    sleep(3000);
    cout << "Hello World 2" << endl;
}
#包括
#包括
使用名称空间std;
无效睡眠(无符号整数毫秒){
时钟目标=毫秒+时钟();
while(目标>时钟());
}
int main(){

coutLinux上没有毫秒级的标准C API,因此您必须使用。POSIX
睡眠时间为秒。

使用C++11可以使用

#包括
#包括
无效睡眠(无符号整数毫秒){
标准时间:毫秒持续时间(毫秒秒);
std::this_thread::sleep_for(dura);
}

我不知道为什么每个人都围着你的问题跳舞而不是回答它

您正在尝试实现自己的类似睡眠的函数,而您的实现在繁忙等待而不是在内核空间中睡眠时(这意味着处理器将“主动”运行代码以睡眠您的程序,而不是告诉机器您的程序正在睡眠,并且它应该运行其他代码),一切正常

问题在于,
clock()
不需要返回毫秒。
clock()
将返回系统时间/从历元开始经过的进程时间,单位为滴答。该时间所用的单位取决于实现

例如,在我的机器上,手册页上说:

描述

函数的作用是:确定自 调用进程的调用,以一个进程的时钟每秒为单位 第二

返回值

函数的作用是:返回所用的时间量,除非出现错误 发生,在这种情况下,返回值为-1

另见

getrusage(2)、时钟(7)

标准

clock()函数符合ISO/IEC 9899:1990(`ISO C90')和 单一UNIX规范(`SUSv3')的第3版,需要 每秒时钟数定义为一百万次


从粗体部分可以看出,滴答声是百万分之一秒,也就是一微秒(不是毫秒)。要“睡眠”3秒钟,您需要调用
sleep(3000000)
和not
sleep(3000)

您可以使用内置
sleep()
函数,该函数以秒为单位,而不是以毫秒为单位,并且必须将
unistd.h
标准库作为内置
sleep()
函数定义在此库下

试试看:

#include <iostream>
#include <unistd.h>

using namespace std;

int main() {
    cout << "Hello World !" << endl;
    sleep(3);   //wait for 3 seconds
    cout << "Hello World 2" << endl;
}
#包括
#包括
使用名称空间std;
int main(){

那不是睡觉,很忙,等等。
#include <iostream>
#include <unistd.h>

using namespace std;

int main() {
    cout << "Hello World !" << endl;
    sleep(3);   //wait for 3 seconds
    cout << "Hello World 2" << endl;
}