Programing

C ++ 프로그램에 시간 지연을 어떻게 추가합니까?

lottogame 2020. 11. 3. 07:34
반응형

C ++ 프로그램에 시간 지연을 어떻게 추가합니까?


C ++ 프로그램에 시간 지연을 추가하려고하는데, 누군가 내가 시도 할 수있는 것에 대한 제안이나 내가 볼 수있는 정보가 있는지 궁금합니다.

이 시간 지연을 구현하는 방법에 대한 자세한 내용을 알고 싶지만 시간 지연을 추가하는 방법에 대한 자세한 정보를 얻을 때까지이를 구현하는 방법에 대해 확신 할 수 없습니다.


Win32 : Sleep(milliseconds)무엇입니까

유닉스 : usleep(microseconds)당신이 원하는 것입니다.

sleep ()은 종종 너무 긴 몇 초만 걸립니다.


C ++ 11에 대한 업데이트 된 답변 :

사용 sleep_forsleep_until기능 :

#include <chrono>
#include <thread>

int main() {
    using namespace std::this_thread; // sleep_for, sleep_until
    using namespace std::chrono; // nanoseconds, system_clock, seconds

    sleep_for(nanoseconds(10));
    sleep_until(system_clock::now() + seconds(1));
}

이러한 기능을 통해 지속적으로 더 나은 해결을 위해 새로운 기능을 추가 할 필요가 더 이상 없다 : sleep, usleep, nanosleep, 등 sleep_forsleep_until통해 어떤 해상도의 값을 받아 들일 수 템플릿 함수입니다 chrono유형; 시간, 초, 펨토초 등

C ++ 14에서는 nanoseconds및에 대한 리터럴 접미사를 사용하여 코드를 더욱 단순화 할 수 있습니다 seconds.

#include <chrono>
#include <thread>

int main() {
    using namespace std::this_thread;     // sleep_for, sleep_until
    using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
    using std::chrono::system_clock;

    sleep_for(10ns);
    sleep_until(system_clock::now() + 1s);
}

실제 휴면 기간은 구현에 따라 다릅니다. 10 나노초 동안 휴면하도록 요청할 수 있지만 구현이 가장 짧은 경우 밀리 초 동안 휴면 상태가 될 수 있습니다.


#include <unistd.h>
usleep(3000000);

이것은 또한 3 초 동안 잠을 자게됩니다. 하지만 숫자를 조금 더 다듬을 수 있습니다.


당신은 같은 간단한 것을 원하십니까

sleep(3);

이것은 스레드가 휴면하는 시간이 휴면 기간에 가깝다는 것을 보장하지 않으며 스레드가 실행을 계속하기 전의 시간이 최소한 원하는 양이 될 것임을 보장 할뿐입니다. 실제 지연은 상황 (특히 문제의 기계에 가해지는 부하)에 따라 다르며 원하는 절전 시간보다 훨씬 더 높을 수 있습니다.

또한 수면이 필요한 이유를 나열하지 않지만 일반적으로 동기화 방법으로 지연을 사용하지 않아야합니다.


마이크로 초 정밀도를 원하면 select (2)를 사용할 수도 있습니다 (usleep (3)이없는 플랫폼에서 작동합니다)

다음 코드는 1.5 초 동안 대기합니다.

#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`

int main() {
    struct timeval t;
    t.tv_sec = 1;
    t.tv_usec = 500000;
    select(0, NULL, NULL, NULL, &t);
}

`


라이브러리 "_sleep(milliseconds);"를 포함하면 (따옴표없이) Win32에서 잘 작동 한다는 것을 알았습니다.chrono

예 :

#include <chrono>

using namespace std;

main
{
    cout << "text" << endl;
    _sleep(10000); // pauses for 10 seconds
}

잠자기 전에 밑줄을 포함했는지 확인하십시오.


Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you're guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.)
Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.

Some additional information:
http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html


You can try this code snippet:

#include<chrono>
#include<thread>

int main(){
    std::this_thread::sleep_for(std::chrono::nanoseconds(10));
    std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));
}

to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file syntax for Sleep() function is Sleep(time_in_ms) as

cout<<"Apple\n";
Sleep(3000);
cout<<"Mango";

OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.


Syntax:

void sleep(unsigned seconds);

sleep() suspends execution for an interval (seconds). With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.


Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.

If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this.

I don't know what OS you are trying to do this on, but for threading and synchronisation you could look to the Boost Threading libraries (Boost Condition Varriable).

Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a 'sleep' is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case. For really short 'waits' you can try an assembly "nop". I highly doubt these are what you are after but without knowing why you need to wait it's hard to be more specific.


On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.

참고URL : https://stackoverflow.com/questions/158585/how-do-you-add-a-timed-delay-to-a-c-program

반응형