2017-10-01 3 views
1

Ich versuche, eine Stoppuhr für die Fehlersuche zu implementieren, wie folgt:C++ std chrono Überlauf

#include <chrono> 

namespace sbstd 
{ 
    class timer 
    { 
    private: 
     bool m_running = false; 
     std::chrono::time_point<std::chrono::system_clock> m_temp; 
     std::chrono::nanoseconds m_time; 
    public: 
     void start() 
     { 
      if (m_running) { throw std::exception("timer already running"); } 
      m_temp = std::chrono::system_clock::now(); 
      m_running = true; 
     } 

     void stop() 
     { 
      if (!m_running) { throw std::exception("timer not started"); } 
      m_time += std::chrono::system_clock::now() - m_temp; 
      m_running = false; 
     } 

     long long get_ms() const 
     { 
      return std::chrono::duration_cast<std::chrono::milliseconds>(m_time).count(); 
     } 
    }; 
} 

Im Hauptverfahren habe ich folgendes:

sbstd::timer t1; 
t1.start(); 
std::this_thread::sleep_for(std::chrono::seconds(5)); 
t1.stop(); 
cout << t1.get_ms(); 

Statt 5000 ich eine negative int erhalten .

Was ist los?

+0

Was ist der Anfangswert von 'm_time'? Wann und wo setzt du es zurück? –

Antwort

1

m_time ist nicht initialisiert, so dass der Wert unbestimmt ist - es ist nur etwas Müllwert. Wahrscheinlich möchten Sie es auf 0 initialisieren - verwenden Sie std::chrono::nanoseconds::zero(). Here ist es in Aktion.

+0

Wenn ich das tue, sagt es mir "std :: chrono :: duration": Verwendung der Klassenvorlage erfordert Vorlage Argumentliste "Ich kann es aber mit einem Konstruktor tun. Weißt du, warum dein Code nicht auf VS2017 kompiliert? –

+0

Entschuldigung! Ich habe es bereits in meinem Schnitt behoben. – Mark

+0

das hat es getan, danke –

Verwandte Themen