Objective: Determine a cross-platform method for obtaining current time and date in C .
Solution:
With the advent of C 11, developers gained access to the powerful std::chrono::system_clock::now() function. This function provides a precise timestamp representing the current system time.
Detailed Example:
The following snippet demonstrates the usage of std::chrono::system_clock::now():
#include <iostream> #include <chrono> #include <ctime> int main() { auto start = std::chrono::system_clock::now(); // Sample heavy computation auto end = std::chrono::system_clock::now(); // Calculate computation duration std::chrono::duration<double> elapsed_seconds = end - start; // Convert to time_t for ctime formatting std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "Computation completed at " << std::ctime(&end_time) << "Elapsed time: " << elapsed_seconds.count() << "s" << std::endl; }
Output:
Computation completed at Mon Oct 2 00:59:08 2017 Elapsed time: 1.88232s
This example showcases the accurate measurement of computation time and the extraction of the system time, including date and time components.
The above is the detailed content of How Can I Efficiently Get the Current Date and Time in C ?. For more information, please follow other related articles on the PHP Chinese website!