Fix RequestContext held too long issue in EventBase
[folly.git] / folly / io / async / test / TimeUtil.h
1 /*
2  * Copyright 2017 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 <iosfwd>
20
21 #include <folly/portability/SysTypes.h>
22
23 namespace folly {
24
25 /**
26  * A class for tracking time durations in test code.
27  *
28  * This is primarily useful for testing timeout functionality.  When comparing
29  * the differences between two TimePoints, it can exclude time spent waiting on
30  * the OS scheduler.  This helps avoid spurious test failures when timeouts are
31  * exceeded by longer than expected simply because the underlying system was
32  * busy and could not schedule this thread in time.
33  */
34 class TimePoint {
35  public:
36   explicit TimePoint(bool set = true)
37     : tid_(0) {
38     if (set) {
39       reset();
40     }
41   }
42
43   void reset();
44
45   bool isUnset() const {
46     return (timeStart_.time_since_epoch().count() == 0 &&
47             timeEnd_.time_since_epoch().count() == 0 &&
48             timeWaiting_.count() == 0);
49   }
50
51   std::chrono::steady_clock::time_point getTime() const {
52     return timeStart_;
53   }
54
55   std::chrono::steady_clock::time_point getTimeStart() const {
56     return timeStart_;
57   }
58
59   std::chrono::steady_clock::time_point getTimeEnd() const {
60     return timeStart_;
61   }
62
63   std::chrono::nanoseconds getTimeWaiting() const {
64     return timeWaiting_;
65   }
66
67   pid_t getTid() const {
68     return tid_;
69   }
70
71  private:
72   std::chrono::steady_clock::time_point timeStart_;
73   std::chrono::steady_clock::time_point timeEnd_;
74   std::chrono::nanoseconds timeWaiting_{0};
75   pid_t tid_;
76 };
77
78 std::ostream& operator<<(std::ostream& os, const TimePoint& timePoint);
79
80 bool checkTimeout(
81     const TimePoint& start,
82     const TimePoint& end,
83     std::chrono::nanoseconds expected,
84     bool allowSmaller,
85     std::chrono::nanoseconds tolerance = std::chrono::milliseconds(5));
86 } // namespace folly