1 /*******************************************************************************
2  * thrill/common/timed_counter.hpp
3  *
4  * Part of Project Thrill - http://project-thrill.org
5  *
6  * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
7  *
8  * All rights reserved. Published under the BSD-2 license in the LICENSE file.
9  ******************************************************************************/
10 
11 #pragma once
12 #ifndef THRILL_COMMON_TIMED_COUNTER_HEADER
13 #define THRILL_COMMON_TIMED_COUNTER_HEADER
14 
15 #include <algorithm>
16 #include <chrono>
17 #include <vector>
18 
19 namespace thrill {
20 namespace common {
21 
22 //! TimedCounter counts the number of \ref Trigger() invokes.
23 //! The time points of these invocations are stored.
24 class TimedCounter
25 {
26 public:
27     using TimePoint = std::chrono::high_resolution_clock::time_point;
28 
29     // no copy ctor
30     TimedCounter(const TimedCounter& that) = delete;
31     // move is okay
TimedCounter(TimedCounter && rhs)32     TimedCounter(TimedCounter&& rhs) {
33         occurences_ = std::move(rhs.occurences_);
34     }
35 
TimedCounter()36     TimedCounter() { }
37 
38     //! Adds the occurences of another TimedCounter to this instance.
39     //! Occurences will be sorted to be ascending
operator +=(const TimedCounter & rhs)40     TimedCounter& operator += (const TimedCounter& rhs) {
41         for (auto& o : rhs.Occurences())
42             occurences_.push_back(o);
43         std::sort(occurences_.begin(), occurences_.end());
44         return *this;
45     }
46 
47     //! Adds occurences of two instances and sorts them ascending
operator +(const TimedCounter & rhs)48     TimedCounter operator + (const TimedCounter& rhs) {
49         TimedCounter t;
50         t += rhs;
51         t += *this;
52         return t;
53     }
54 
55     //! Registers a new Occurence on this TimedCounter
Trigger()56     void Trigger() {
57         occurences_.push_back(timestamp());
58     }
59 
60     //! Drops all Occurences of this timer.
Reset()61     void Reset() {
62         occurences_.clear();
63     }
64 
65     //! Returns the number of Occurences on this timer
Count() const66     size_t Count() const {
67         return occurences_.size();
68     }
69 
70     //! Returns the Occurences of this timer.
Occurences() const71     std::vector<TimePoint> Occurences() const {
72         return occurences_;
73     }
74 
75 private:
timestamp()76     inline TimePoint timestamp() {
77         return std::chrono::high_resolution_clock::now();
78     }
79 
80     std::vector<TimePoint> occurences_;
81 };
82 
83 } // namespace common
84 } // namespace thrill
85 
86 #endif // !THRILL_COMMON_TIMED_COUNTER_HEADER
87 
88 /******************************************************************************/
89