2016-10-11 99 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'; 
}