如何在 C++ 中使用以下代码生成 stopwatch/countdown?

How can I generate a stopwatch/countdown with the following code in C++?

我正在尝试创建一个计时器函数,该函数打印一个 2 分钟的计时器(以 M:S 形式),该计时器会自行计时。我有以下代码:

    void startTimer(){
    srand(time(0));

    clock_t start_t, end_t;
    clock_t start = clock();        
    clock_t end = clock();
    float seconds = (float)(end - start) / CLOCKS_PER_SEC;

    printf("%d", start, seconds);
    }

我不是很懂你的代码。

  • 你想用你的随机数做什么?
  • 为什么要声明 start_t 和 end_t?
  • 您认为开始和结束会有什么价值?
  • 您想打印什么?

如果你想要一个 2 分钟的计时器,也许你可以使用一个从 120 到 0 的循环,在循环中使用 printf(分钟 = 索引/60 和秒 = 索引 % 60)和 1 秒睡眠。这将阻塞循环的线程。那是问题吗?

如果是,您可能想看看其他解决方案,例如将循环移动到另一个线程中

您拥有的代码可以测量 运行 一段代码所花费的时间。您在这里需要的只是:

  • 打印倒计时
  • 睡一秒

循环执行。

#include <iostream>
#include <unistd.h>


int main(){
  for (int i = 120; i >=0; i--){
    std::cout << std::to_string(i/60) <<":" << std::to_string(i%60) <<std::endl; 
    sleep(1);
  }
  return 0;
}