Copyright 2014->2015
[folly.git] / folly / io / async / test / TimeUtil.h
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17
18 #include <chrono>
19 #include <iostream>
20
21 namespace folly {
22
23 class TimePoint {
24  public:
25   explicit TimePoint(bool set = true)
26     : tid_(0) {
27     if (set) {
28       reset();
29     }
30   }
31
32   void reset();
33
34   bool isUnset() const {
35     return (timeStart_.time_since_epoch().count() == 0 &&
36             timeEnd_.time_since_epoch().count() == 0 &&
37             timeWaiting_.count() == 0);
38   }
39
40   std::chrono::system_clock::time_point getTime() const {
41     return timeStart_;
42   }
43
44   std::chrono::system_clock::time_point getTimeStart() const {
45     return timeStart_;
46   }
47
48   std::chrono::system_clock::time_point getTimeEnd() const {
49     return timeStart_;
50   }
51
52   std::chrono::milliseconds getTimeWaiting() const {
53     return timeWaiting_;
54   }
55
56   pid_t getTid() const {
57     return tid_;
58   }
59
60  private:
61   std::chrono::system_clock::time_point timeStart_;
62   std::chrono::system_clock::time_point timeEnd_;
63   std::chrono::milliseconds timeWaiting_{0};
64   pid_t tid_;
65 };
66
67 std::ostream& operator<<(std::ostream& os, const TimePoint& timePoint);
68
69 bool checkTimeout(const TimePoint& start,
70                   const TimePoint& end,
71                   std::chrono::milliseconds expectedMS,
72                   bool allowSmaller,
73                   std::chrono::milliseconds tolerance =
74                   std::chrono::milliseconds(5));
75
76 }