Home >Backend Development >C++ >How Can I Precisely Get the Current Date and Time in C ?
How to Obtain Current Time and Date with Precision in C
In the realm of C programming, accessing the current date and time accurately is a common necessity. Before C 11, there were limited and somewhat antiquated methods to retrieve this information. However, with the advent of C 11 came a modern and versatile solution.
Solution: std::chrono::system_clock::now()
Since C 11, the standard library introduced the std::chrono::system_clock class, which provides a reliable and cross-platform way to access the current system time. The std::chrono::system_clock::now() method returns a system_clock::time_point object that represents the current time.
Example Code:
To illustrate its usage, consider the following example code:
#include <iostream> #include <chrono> #include <ctime> int main() { // Get the current time auto start = std::chrono::system_clock::now(); // Perform some computation here // Get the end time auto end = std::chrono::system_clock::now(); // Calculate the elapsed time in seconds std::chrono::duration<double> elapsed_seconds = end - start; // Convert the end time to a std::time_t std::time_t end_time = std::chrono::system_clock::to_time_t(end); // Print the result std::cout << "Finished computation at: " << std::ctime(&end_time) << std::endl; std::cout << "Elapsed time: " << elapsed_seconds.count() << " seconds" << std::endl; return 0; }
Output:
When executed, this code will output something similar to:
Finished computation at: Mon Oct 2 00:59:08 2017 Elapsed time: 1.23456 seconds
The system_clock::now() method provides high-precision access to the current time and is suitable for various applications, such as performance profiling and time-sensitive calculations.
The above is the detailed content of How Can I Precisely Get the Current Date and Time in C ?. For more information, please follow other related articles on the PHP Chinese website!