public:
explicit AutoTimer(StringPiece msg = "")
: destructionMessage_(msg.str()),
- start_(Clock::now()) {
+ start_(Clock::now()),
+ minTimeToLog_(0.0) {
}
// Automatically generate a log message using to<std::string>. Makes it
template<typename... Args>
explicit AutoTimer(Args&&... args)
: destructionMessage_(to<std::string>(std::forward<Args>(args)...)),
- start_(Clock::now()) {
+ start_(Clock::now()),
+ minTimeToLog_(0.0) {
+ }
+
+ // We don't expose this in the constructor because it creates ambiguity with
+ // the variadic template constructor.
+ void setMinTimeToLog(double t) {
+ minTimeToLog_ = t;
}
// It doesn't really make sense to copy/move an AutoTimer
double duration = std::chrono::duration_cast<std::chrono::duration<double>>(
now - start_
).count();
- Logger()(msg, duration);
+ if (duration >= minTimeToLog_) {
+ Logger()(msg, duration);
+ }
start_ = Clock::now(); // Don't measure logging time
return duration;
}
const std::string destructionMessage_;
std::chrono::time_point<Clock> start_;
+ double minTimeToLog_;
};
template<GoogleLoggerStyle Style>
-struct GoogleLogger {
+struct GoogleLogger final {
void operator()(StringPiece msg, double sec) const {
if (msg.empty()) {
return;
t.log("First message");
t.log("Second message");
}
+
+TEST(TestAutoTimer, HandleMinLogTime) {
+ StubClock::t = 1;
+ AutoTimer<StubLogger, StubClock> timer;
+ timer.setMinTimeToLog(3);
+ StubClock::t = 3;
+ // only 2 "seconds" have passed, so this shouldn't log
+ StubLogger::t = 0;
+ ASSERT_EQ(2.0, timer.log("foo"));
+ ASSERT_EQ(0, StubLogger::t);
+}