Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function runs in windows perfectly but not linux?

Tags:

c++

linux

I am trying to write a simple c++ function sleep(int millisecond) that will sleep the program for user-specific millisecond.

Here is my code:

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

The sleep() function works perfectly when I run this code on windows but doesn't work on Linux. Can anyone figure it out what's wrong with my code?

like image 750
user3687895 Avatar asked Dec 14 '22 17:12

user3687895


2 Answers

I don't know why everyone is dancing around your question instead of answering it.

You are attempting to implement your own sleep-like function, and your implementation, while it does busy wait instead of sleeping in the kernelspace (meaning that processor will be "actively" running code to sleep your program, instead of telling the machine your program is sleeping and it should run other code), is just fine.

The problem is that clock() is not required to return milliseconds. clock() will return system time/process time elapsed in ticks from epoch. What unit that time will take depends on the implementation.

For instance, on my machine, this is what the man page says:

DESCRIPTION

The clock() function determines the amount of processor time used since the invocation of the calling process, measured in CLOCKS_PER_SECs of a second.

RETURN VALUES

The clock() function returns the amount of time used unless an error occurs, in which case the return value is -1.

SEE ALSO

getrusage(2), clocks(7)

STANDARDS

The clock() function conforms to ISO/IEC 9899:1990 (``ISO C90'') and Version 3 of the Single UNIX Specification (``SUSv3'') which requires CLOCKS_PER_SEC to be defined as one million.

As you can see from the bolded part, a tick is one-one-millionth of a second, aka a microsecond (not a millisecond). To "sleep" for 3 seconds, you'll need to call your sleep(3000000) and not sleep(3000).

like image 155
Mahmoud Al-Qudsi Avatar answered Dec 25 '22 07:12

Mahmoud Al-Qudsi


With C++11 you can use sleep_for.

#include <chrono>
#include <thread>

void sleep(unsigned int mseconds) {
    std::chrono::milliseconds dura( mseconds);
    std::this_thread::sleep_for( dura );
}
like image 29
sjdowling Avatar answered Dec 25 '22 08:12

sjdowling