How to Get Time in Milliseconds in C++?

In programming measuring accurate time is a common requirement for most software development packages. In C++, we have the std::chrono library with various functions for durations, time, and clocks. In this article, we will learn how to get time in milliseconds in C++.

For Example,

Input:
Current system time.

Output:
Current time in milliseconds since epoch: 1716440609637

Get Current Time in Milliseconds

To get the time in milliseconds we can use the methods of <chrono> library. First, get the current time from the system clock by calling the std::chrono::system_clock::now() function and then convert the current time to time since epoch by using the time_since_epoch() function. Finally convert duration to milliseconds by using std::chrono::duration_cast with std::chrono::milliseconds and count() function.

C++ Program to Get Time in Milliseconds

The below program demonstrates how we can get time in milliseconds in C++.

C++
// C++ program to get the current time and convert it into
// milliseconds

#include <chrono>
#include <iostream>

using namespace std;

int main()
{
    // Get the current time from the system clock
    auto now = chrono::system_clock::now();

    // Convert the current time to time since epoch
    auto duration = now.time_since_epoch();

    // Convert duration to milliseconds
    auto milliseconds
        = chrono::duration_cast<chrono::milliseconds>(
              duration)
              .count();

    // Print the result
    cout << "Current time in milliseconds is: "
         << milliseconds << endl;

    return 0;
}

Output
Current time in milliseconds is: 1716441405153

Time Complexity: O(1)
Auxilliary Space: O(1)

Note: The std::chrono::system_clock::now() and std::chrono::duration_cast are defined in C++11 standard. So, these function may not run with older compilers.