You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中输出毫秒级时间?附作业输入计时需求

如何在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_clock is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:44:41