Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

function like sleep c++ 14

  1. User

    function like sleep c++ 14

  2. Assistant

    In C++, if you want to introduce a delay or pause the execution of your program, you can use the standard library. In C++14, the <chrono> header provides convenient facilities for dealing with time intervals, and you can use this along with the <thread> library for sleeping.

    Here's how you can use std::this_thread::sleep_for to create a sleep-like function in C++14:

    #include <iostream>
    #include <chrono>
    #include <thread>
    
    int main() {
        std::cout << "Starting...\n";
    
        // Sleep for 2 seconds
        std::this_thread::sleep_for(std::chrono::seconds(2));
    
        std::cout << "Finished waiting for 2 seconds.\n";
    
        return 0;
    }
    

    Explanation:

    • #include <chrono>: This includes the chrono library which contains utilities for time manipulation.
    • #include <thread>: This includes capabilities for multithreading, notably std::this_thread::sleep_for.
    • std::this_thread::sleep_for: This function suspends the execution of the current thread for the specified duration.
    • std::chrono::seconds(2): This specifies a duration of 2 seconds. You have other duration types like std::chrono::milliseconds, std::chrono::microseconds, etc., for different time scales.

    You can replace std::chrono::seconds with other time units depending on the precision you'd like, e.g., for milliseconds or microseconds. Ensure your compiler is set to at least C++11 mode since these features were introduced in C++11 and continue to be available in C++14.