2016-10-11 91 views
-1

我已经创建了一个函数,在选择用户之后计算秒数。这一切都有效,但它可以做得更聪明,更高效?因为它看起来很重,很慢。有没有解决这个问题的库?或者我们如何解决它?C++秒计数器

这里是我的代码:

#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; 
} 
+4

使用'的std :: chrono'见请参考http://en.cppreference.com/w/cpp/chrono – PRP

+0

在循环的每次迭代中,你会不会只是“睡(1)”? – selbie

+0

哦!谢谢 - 没有想到仅仅使用睡眠计数法:D非常感谢 – Holycrabbe

回答

0

您可以使用该库<chrono>(因为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'; 
}