Acquiring the Current Time and Date in C : A Cross-Platform Approach
Obtaining the current date and time is a common task in various programming scenarios. C offers a cross-platform solution through the C 11 standard, enabling developers to retrieve this information consistently across different operating systems.
Solution Using std::chrono::system_clock::now()
The std::chrono library, introduced in C 11, provides a standardized interface for working with time and dates. The function std::chrono::system_clock::now() returns a system_clock object representing the current system time.
Example Implementation
Below is an example code snippet demonstrating how to use std::chrono::system_clock::now():
#include <iostream> #include <chrono> #include <ctime> int main() { auto start = std::chrono::system_clock::now(); // Some computation here auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "finished computation at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s" << std::endl; return 0; }
When you run this code, it will print the current time, followed by the duration of any computations performed between the start and end time measurements.
The above is the detailed content of How Can I Get the Current Date and Time in C Cross-Platform?. For more information, please follow other related articles on the PHP Chinese website!