【问题标题】:C++ second counterC++ 第二个计数器
【发布时间】:2016-10-11 06:49:21
【问题描述】:

我创建了一个在用户选择后计算秒数的函数。这一切都有效,但它可以做得更聪明、更高效吗?因为它看起来很重很慢。有没有解决这个问题的库?或者我们怎样才能绕过它?

这是我的代码:

#include <ctime>
#include <iomanip>
#include <iostream>

using namespace std;

int main() {
    double a,c, x,b;

    int nutid=0;

    cout<<"Please enter a number: ";
    cin>>a;
    x = time(0);
    c = a-1;

    while (true) {
        if (!cin) {
            cout<<"... Error";
            break;
        }
        else {
            b=time(0)-x;

            if(b>nutid){
                cout<<setprecision(11)<<b<<endl;
                nutid = b+c;
            }
        }
    }

    return 0;
}

【问题讨论】:

  • 使用std::chrono 在此处查看参考en.cppreference.com/w/cpp/chrono
  • 在循环的每次迭代中,您不希望 sleep(1) 做什么?
  • 哦!谢谢 - 没想到只使用睡眠作为计数方法:D 非常感谢

标签: c++ timer counter


【解决方案1】:

您可以使用库&lt;chrono&gt;(自c++11)测量时间

例子:

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;

int main() {
    auto start = high_resolution_clock::now();

    // your code here

    auto end = high_resolution_clock::now();
    // you can also use 'chrono::microseconds' etc.
    cout << duration_cast<seconds>(end - start).count() << '\n';
}

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 2021-05-19
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多