如何在C++中输出毫秒级时间?附作业输入计时需求
Hey Matt! Glad to help you get that millisecond-level timing working for your assignment. Let's start by breaking down what's going on with your current code, then fix it up.
First, a quick typo catch: you wrote using namesapce chrono; instead of using namespace chrono; — that'll cause a compile error, so make sure to fix that first!
Your current code uses time_t, which only tracks time down to the second — that's why you can't get millisecond precision. The <chrono> library you already included is perfect for this though, since it supports high-resolution clocks.
Here's a revised version of your code that tracks time in milliseconds, plus a check for the 10-second input limit you need:
#include <iostream> #include <chrono> #include <cstdio> // Replaced C-style <stdio.h> with C++-style header using namespace std; using namespace chrono; // Fixed the typo here int main() { int f; // Start the high-resolution timer auto start_time = steady_clock::now(); cout << "Please enter a number within 10 seconds: "; cin >> f; // Get the end time auto end_time = steady_clock::now(); // Calculate elapsed time in milliseconds auto elapsed_ms = duration_cast<milliseconds>(end_time - start_time); double elapsed_seconds = elapsed_ms.count() / 1000.0; // Convert to seconds if needed // Output both formats for clarity printf("Elapsed time is %.3lf seconds (or %lld milliseconds).\n", elapsed_seconds, elapsed_ms.count()); // Check if the input took longer than 10 seconds if (elapsed_ms.count() > 10000) { cout << "Oops! You took too long — the time limit is 10 seconds." << endl; } return 0; }
Let me explain a few key parts:
steady_clockis the best choice for timing operations because it's not affected by system time changes (like if someone adjusts the clock while your program runs).duration_cast<milliseconds>(...)converts the time difference between start and end into a millisecond count.elapsed_ms.count()gives you the raw number of milliseconds, which you can easily convert to seconds by dividing by 1000.0.
If you want even finer precision (like fractions of a millisecond), you can use duration<double, milli> instead:
auto elapsed_ms_precise = duration<double, milli>(end_time - start_time); cout << "Elapsed time (precise): " << elapsed_ms_precise.count() << " ms" << endl;
This will output something like 1234.567 ms instead of just whole milliseconds.
内容的提问来源于stack exchange,提问作者Matt

