diff --git a/ortools/util/time_limit.cc b/ortools/util/time_limit.cc index d856e404b6..ab3f6ad3a7 100644 --- a/ortools/util/time_limit.cc +++ b/ortools/util/time_limit.cc @@ -14,12 +14,17 @@ #include "ortools/util/time_limit.h" #include +#include #include #include #include #include +#include "absl/flags/flag.h" +#include "absl/log/die_if_null.h" +#include "absl/log/log.h" #include "absl/strings/str_cat.h" +#include "absl/time/time.h" ABSL_FLAG(bool, time_limit_use_usertime, false, "If true, rely on the user time in the TimeLimit class. This is " @@ -31,6 +36,13 @@ namespace operations_research { const double TimeLimit::kSafetyBufferSeconds = 1e-4; const int TimeLimit::kHistorySize = 100; +TimeLimit::TimeLimit(double limit_in_seconds, double deterministic_limit) + : safety_buffer_ns_(static_cast(kSafetyBufferSeconds * 1e9)), + running_max_(kHistorySize), + external_boolean_as_limit_(nullptr) { + ResetTimers(limit_in_seconds, deterministic_limit); +} + std::string TimeLimit::DebugString() const { std::string buffer = absl::StrCat( "Time left: ", (GetTimeLeft()), diff --git a/ortools/util/time_limit.h b/ortools/util/time_limit.h index 799250c982..cf8fbca432 100644 --- a/ortools/util/time_limit.h +++ b/ortools/util/time_limit.h @@ -462,14 +462,26 @@ class NestedTimeLimit { TimeLimit time_limit_; }; -// ################## Implementations below ##################### +class TimeLimitCheckEveryNCalls { + public: + TimeLimitCheckEveryNCalls(int N, TimeLimit* time_limit) + : time_limit_(time_limit), count_(0), frequency_(N) {} -inline TimeLimit::TimeLimit(double limit_in_seconds, double deterministic_limit) - : safety_buffer_ns_(static_cast(kSafetyBufferSeconds * 1e9)), - running_max_(kHistorySize), - external_boolean_as_limit_(nullptr) { - ResetTimers(limit_in_seconds, deterministic_limit); -} + bool LimitReached() { + if (count_++ == frequency_) { + if (time_limit_->LimitReached()) return true; + count_ = 0; + } + return false; + } + + private: + TimeLimit* time_limit_; + int count_; + const int frequency_; +}; + +// ################## Implementations below ##################### inline void TimeLimit::ResetTimers(double limit_in_seconds, double deterministic_limit) {