c++ - 使用时钟()输出持续时间,但输出相乘
问题描述
所以,我想显示程序以秒为单位打开的持续时间,但它显示的是多秒而不是一个字符。前任。1 到 11111 这是代码:
int main() {
clock_t start;
double duration;
int seconds;
start = clock();
while (true) {
if ((clock() - start) % CLOCKS_PER_SEC == 0) {
cout << (clock() - start) / (double)CLOCKS_PER_SEC;
}
}
}
输出 :
01111111111111111111111222222222233333333333334444444445555555556666666666666667777777777777
帮我解决这个问题
解决方案
你的if
支票完全错了。想象一下,如果您的while
循环运行两次并且没有变化,clock()
因为它循环非常快。它要么输出两次,要么不输出任何时间。这不可能是对的。
正确的检查是查看自上次生成输出以来是否已过去至少一秒钟。
clock_t last_output;
start = last_output = clock();
while (true) {
if (clock() > (last_output + CLOCKS_PER_SEC)){
last_output += CLOCKS_PER_SEC;
cout << (clock() - start) / (double)CLOCKS_PER_SEC;
}
}
这是完整的代码:
#include <time.h>
#include <iostream>
int main()
{
clock_t start, last_output;
start = last_output = clock();
while (true)
{
if (clock() > (last_output + CLOCKS_PER_SEC))
{
last_output += CLOCKS_PER_SEC;
std::cout << (clock() - start) / (double)CLOCKS_PER_SEC << std::endl;
}
}
}
推荐阅读
- sql - 多个插入/更新的 SQL 前缀
- php - Messenger 工作人员在 Symfony 4 测试中闲置/不“工作”
- spring-boot - 使用 Spring Boot 的 JSP
- python-3.x - 如何从另一个脚本执行代码并传递参数
- powershell - 带有输入文件的 Power Shell 上的 Active Directory 查询
- bootstrap-4 - 如何在引导程序 4 中更改指示器的颜色
- r - 添加缺少的小数(001=0.01 和 01=0.1)
- r - 计算一列的重复观察值但另一列的值不同的平均值
- java - 如何使用 Java 在 Druid Timeseries 数据库中加载和查询数据
- android - Android 11 - Kiosk 模式锁屏 NFC 问题