xref: /glogg/src/perfcounter.h (revision 6e2e573c451ec24d720c967fab68538eaa3f3ab5)
1 /*
2  * Copyright (C) 2015 Nicolas Bonnefon and other contributors
3  *
4  * This file is part of glogg.
5  *
6  * glogg is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * glogg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with glogg.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <chrono>
21 
22 // This class is a counter that remembers the number of events occuring within one second
23 // it can be used for performance measurement (e.g. FPS)
24 
25 class PerfCounter {
26   public:
27     PerfCounter() {}
28 
29     // Count a new event, returns true if it has been counted.
30     // If the function returns false, it indicates the current second is elapsed
31     // and the user should read and reset the counter before re-adding the event.
32     bool addEvent() {
33         using namespace std::chrono;
34         if ( counter_ == 0 )
35             first_event_date_ = steady_clock::now();
36 
37         if ( duration_cast<microseconds>(
38                     steady_clock::now() - first_event_date_ ).count() < 1000000 ) {
39             ++counter_;
40             return true;
41         }
42         else {
43             return false;
44         }
45     }
46 
47     // Read and reset the counter. Returns the number of events that occured in the
48     // previous second.
49     uint32_t readAndReset() {
50         uint32_t value = counter_;
51         counter_ = 0;
52         return value;
53     }
54 
55   private:
56     uint32_t counter_ = 0;
57     std::chrono::steady_clock::time_point first_event_date_;
58 };
59