Skip to content

[cpp,c++,std::chrono] time 01: Time Measurement

Get Current Time

std::chrono::system_clock::now
namespace chrono = std::chrono;
auto time_now = chrono::system_clock::now();
If you do not want auto:
chrono::time_point time_now = chrono::system_clock::now();

Time Measurement Using std::chrono

Test how much time a process is running.
auto start = chrono::system_clock::now();

do_a_busy_job;

auto end = chrono::system_clock::now();
A full example:
#include <chrono>
#include <thread>
#include <iostream>

namespace chrono = std::chrono;

int main() {
    auto start = chrono::system_clock::now();
    std::this_thread::sleep_for(std::chrono::seconds(3));
    auto end = chrono::system_clock::now();

    auto elapsed = chrono::duration_cast(end-start);

    auto secs = elapsed.count();

    std::cout << secs << " secs" << std::endl; // Print the secs.

    static_assert(std::signed_integral); // OK
}
If you do not want auto:
#include <chrono>
#include <thread>
#include <iostream>

namespace chrono = std::chrono;

int main() {
    chrono::time_point start = chrono::system_clock::now();
    std::this_thread::sleep_for(std::chrono::seconds(3));
    chrono::time_point end = chrono::system_clock::now();

    chrono::duration duration = end - start;

    chrono::duration> elapsed = chrono::duration_cast(duration);

    std::int64_t secs = elapsed.count();

    std::cout << secs << " secs" << std::endl; // Print the secs.

    static_assert(std::signed_integral); // OK
}

std::cout std::chrono::time_point

operator<< for std::chrono::time_point

Visual CPP Only (msvs)
#include <chrono>
#include <iostream>

namespace chrono = std::chrono;

int main() {
    auto time = chrono::system_clock::now();
    std::cout << time << std::endl;

    chrono::time_point time2 = chrono::system_clock::now();
    std::cout << time2 << std::endl;
}
Result:
2022-06-26 09:10:34.2896099
2022-06-26 09:10:34.2907862

Trackbacks

No Trackbacks

Comments

Display comments as Linear | Threaded

No comments

Add Comment

E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.
CAPTCHA

Form options

Submitted comments will be subject to moderation before being displayed.

@cppfx.xyz