C++ Reference

C++ Reference: CP-SAT

time_limit.h
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #ifndef OR_TOOLS_UTIL_TIME_LIMIT_H_
15 #define OR_TOOLS_UTIL_TIME_LIMIT_H_
16 
17 #include <algorithm>
18 #include <atomic>
19 #include <cstdlib>
20 #include <limits>
21 #include <memory>
22 #include <string>
23 
24 #include "absl/container/flat_hash_map.h"
25 #include "absl/memory/memory.h"
26 #include "absl/synchronization/mutex.h"
27 #include "absl/time/clock.h"
28 #include "ortools/base/commandlineflags.h"
29 #include "ortools/base/logging.h"
30 #include "ortools/base/macros.h"
31 #include "ortools/base/timer.h"
32 #include "ortools/util/running_stat.h"
33 #ifdef HAS_PERF_SUBSYSTEM
34 #include "exegesis/exegesis/itineraries/perf_subsystem.h"
35 #endif // HAS_PERF_SUBSYSTEM
36 
41 DECLARE_bool(time_limit_use_usertime);
42 
47 DECLARE_bool(time_limit_use_instruction_count);
48 
49 namespace operations_research {
50 
103 // TODO(user): The expression "deterministic time" should be replaced with
104 // "number of operations" to avoid confusion with "real" time.
105 class TimeLimit {
106  public:
107  static const double kSafetyBufferSeconds; // See the .cc for the value.
108  static const int kHistorySize;
109 
121  explicit TimeLimit(
122  double limit_in_seconds,
123  double deterministic_limit = std::numeric_limits<double>::infinity(),
124  double instruction_limit = std::numeric_limits<double>::infinity());
125 
126  TimeLimit() : TimeLimit(std::numeric_limits<double>::infinity()) {}
127  TimeLimit(const TimeLimit&) = delete;
128  TimeLimit& operator=(const TimeLimit&) = delete;
129 
134  static std::unique_ptr<TimeLimit> Infinite() {
135  return absl::make_unique<TimeLimit>(
136  std::numeric_limits<double>::infinity(),
137  std::numeric_limits<double>::infinity(),
138  std::numeric_limits<double>::infinity());
139  }
140 
144  static std::unique_ptr<TimeLimit> FromDeterministicTime(
145  double deterministic_limit) {
146  return absl::make_unique<TimeLimit>(
147  std::numeric_limits<double>::infinity(), deterministic_limit,
148  std::numeric_limits<double>::infinity());
149  }
150 
157  // TODO(user): Support adding instruction count limit from parameters.
158  template <typename Parameters>
159  static std::unique_ptr<TimeLimit> FromParameters(
160  const Parameters& parameters) {
161  return absl::make_unique<TimeLimit>(
162  parameters.max_time_in_seconds(), parameters.max_deterministic_time(),
163  std::numeric_limits<double>::infinity());
164  }
165 
171  void SetInstructionLimit(double instruction_limit) {
172  instruction_limit_ = instruction_limit;
173  }
174 
179  // TODO(user): Use an exact counter for counting instructions. The
180  // PMU counter returns the instruction count value as double since there may
181  // be sampling issues.
182  double ReadInstructionCounter();
183 
190  bool LimitReached();
191 
204  double GetTimeLeft() const;
205 
212  double GetDeterministicTimeLeft() const {
213  return std::max(0.0, deterministic_limit_ - elapsed_deterministic_time_);
214  }
215 
219  double GetInstructionsLeft();
220 
226  inline void AdvanceDeterministicTime(double deterministic_duration) {
227  DCHECK_LE(0.0, deterministic_duration);
228  elapsed_deterministic_time_ += deterministic_duration;
229  }
230 
240  inline void AdvanceDeterministicTime(double deterministic_duration,
241  const char* counter_name) {
242  AdvanceDeterministicTime(deterministic_duration);
243 #ifndef NDEBUG
244  deterministic_counters_[counter_name] += deterministic_duration;
245 #endif
246  }
247 
251  double GetElapsedTime() const {
252  return 1e-9 * (absl::GetCurrentTimeNanos() - start_ns_);
253  }
254 
261  return elapsed_deterministic_time_;
262  }
263 
275  std::atomic<bool>* external_boolean_as_limit) {
276  external_boolean_as_limit_ = external_boolean_as_limit;
277  }
278 
282  std::atomic<bool>* ExternalBooleanAsLimit() const {
283  return external_boolean_as_limit_;
284  }
285 
290  template <typename Parameters>
291  void ResetLimitFromParameters(const Parameters& parameters);
292  void MergeWithGlobalTimeLimit(TimeLimit* other);
293 
297  std::string DebugString() const;
298 
299  private:
300  void ResetTimers(double limit_in_seconds, double deterministic_limit,
301  double instruction_limit);
302 
303  std::string GetInstructionRetiredEventName() const {
304  return "inst_retired:any_p:u";
305  }
306 
307  mutable int64 start_ns_; // Not const! this is initialized after instruction
308  // counter initialization.
309  int64 last_ns_;
310  int64 limit_ns_; // Not const! See the code of LimitReached().
311  const int64 safety_buffer_ns_;
312  RunningMax<int64> running_max_;
313 
314  // Only used when FLAGS_time_limit_use_usertime is true.
315  UserTimer user_timer_;
316  double limit_in_seconds_;
317 
318  double deterministic_limit_;
319  double elapsed_deterministic_time_;
320 
321  std::atomic<bool>* external_boolean_as_limit_;
322 
323 #ifdef HAS_PERF_SUBSYSTEM
324  // PMU counter to help count the instructions.
325  exegesis::PerfSubsystem perf_subsystem_;
326 #endif // HAS_PERF_SUBSYSTEM
327  // Given limit in terms of number of instructions.
328  double instruction_limit_;
329 
330 #ifndef NDEBUG
331  // Contains the values of the deterministic time counters.
332  absl::flat_hash_map<std::string, double> deterministic_counters_;
333 #endif
334 
335  friend class NestedTimeLimit;
336  friend class ParallelTimeLimit;
337 };
338 
339 // Wrapper around TimeLimit to make it thread safe and add Stop() support.
341  public:
342  explicit SharedTimeLimit(TimeLimit* time_limit)
343  : time_limit_(time_limit), stopped_boolean_(false) {
344  // We use the one already registered if present or ours otherwise.
345  stopped_ = time_limit->ExternalBooleanAsLimit();
346  if (stopped_ == nullptr) {
347  stopped_ = &stopped_boolean_;
348  time_limit->RegisterExternalBooleanAsLimit(stopped_);
349  }
350  }
351 
353  if (stopped_ == &stopped_boolean_) {
354  time_limit_->RegisterExternalBooleanAsLimit(nullptr);
355  }
356  }
357 
358  bool LimitReached() const {
359  // Note, time_limit_->LimitReached() is not const, and changes internal
360  // state of time_limit_, hence we need a writer's lock.
361  absl::MutexLock lock(&mutex_);
362  return time_limit_->LimitReached();
363  }
364 
365  void Stop() {
366  absl::MutexLock lock(&mutex_);
367  *stopped_ = true;
368  }
369 
370  void UpdateLocalLimit(TimeLimit* local_limit) {
371  absl::MutexLock lock(&mutex_);
372  local_limit->MergeWithGlobalTimeLimit(time_limit_);
373  }
374 
375  void AdvanceDeterministicTime(double deterministic_duration) {
376  absl::MutexLock lock(&mutex_);
377  time_limit_->AdvanceDeterministicTime(deterministic_duration);
378  }
379 
380  double GetTimeLeft() const {
381  absl::ReaderMutexLock lock(&mutex_);
382  return time_limit_->GetTimeLeft();
383  }
384 
386  absl::ReaderMutexLock lock(&mutex_);
387  return time_limit_->GetElapsedDeterministicTime();
388  }
389 
390  private:
391  mutable absl::Mutex mutex_;
392  TimeLimit* time_limit_ GUARDED_BY(mutex_);
393  std::atomic<bool> stopped_boolean_ GUARDED_BY(mutex_);
394  std::atomic<bool>* stopped_ GUARDED_BY(mutex_);
395 };
396 
428  public:
433  NestedTimeLimit(TimeLimit* base_time_limit, double limit_in_seconds,
434  double deterministic_limit);
435 
440 
448  template <typename Parameters>
449  static std::unique_ptr<NestedTimeLimit> FromBaseTimeLimitAndParameters(
450  TimeLimit* time_limit, const Parameters& parameters) {
451  return absl::make_unique<NestedTimeLimit>(
452  time_limit, parameters.max_time_in_seconds(),
453  parameters.max_deterministic_time());
454  }
455 
462  TimeLimit* GetTimeLimit() { return &time_limit_; }
463 
464  private:
465  TimeLimit* const base_time_limit_;
466  TimeLimit time_limit_;
467 
468  DISALLOW_COPY_AND_ASSIGN(NestedTimeLimit);
469 };
470 
471 // ################## Implementations below #####################
472 
473 inline TimeLimit::TimeLimit(double limit_in_seconds, double deterministic_limit,
474  double instruction_limit)
475  : safety_buffer_ns_(static_cast<int64>(kSafetyBufferSeconds * 1e9)),
476  running_max_(kHistorySize),
477  external_boolean_as_limit_(nullptr) {
478  ResetTimers(limit_in_seconds, deterministic_limit, instruction_limit);
479 }
480 
481 inline void TimeLimit::ResetTimers(double limit_in_seconds,
482  double deterministic_limit,
483  double instruction_limit) {
484  if (external_boolean_as_limit_ != nullptr) {
485  *external_boolean_as_limit_ = false;
486  }
487  elapsed_deterministic_time_ = 0.0;
488  deterministic_limit_ = deterministic_limit;
489  instruction_limit_ = instruction_limit;
490 
491  if (FLAGS_time_limit_use_usertime) {
492  user_timer_.Start();
493  limit_in_seconds_ = limit_in_seconds;
494  }
495 #ifdef HAS_PERF_SUBSYSTEM
496  if (FLAGS_time_limit_use_instruction_count) {
497  perf_subsystem_.CleanUp();
498  perf_subsystem_.AddEvent(GetInstructionRetiredEventName());
499  perf_subsystem_.StartCollecting();
500  }
501 #endif // HAS_PERF_SUBSYSTEM
502  start_ns_ = absl::GetCurrentTimeNanos();
503  last_ns_ = start_ns_;
504  limit_ns_ = limit_in_seconds >= 1e-9 * (kint64max - start_ns_)
505  ? kint64max
506  : static_cast<int64>(limit_in_seconds * 1e9) + start_ns_;
507 }
508 
509 template <typename Parameters>
510 inline void TimeLimit::ResetLimitFromParameters(const Parameters& parameters) {
511  ResetTimers(parameters.max_time_in_seconds(),
512  parameters.max_deterministic_time(),
513  std::numeric_limits<double>::infinity());
514 }
515 
517  if (other == nullptr) return;
518  ResetTimers(
519  std::min(GetTimeLeft(), other->GetTimeLeft()),
521  std::numeric_limits<double>::infinity());
522  if (other->ExternalBooleanAsLimit() != nullptr) {
524  }
525 }
526 
528 #ifdef HAS_PERF_SUBSYSTEM
529  if (FLAGS_time_limit_use_instruction_count) {
530  return perf_subsystem_.ReadCounters().GetScaledOrDie(
531  GetInstructionRetiredEventName());
532  }
533 #endif // HAS_PERF_SUBSYSTEM
534  return 0;
535 }
536 
537 inline bool TimeLimit::LimitReached() {
538  if (external_boolean_as_limit_ != nullptr &&
539  external_boolean_as_limit_->load()) {
540  return true;
541  }
542 
543  if (GetDeterministicTimeLeft() <= 0.0) {
544  return true;
545  }
546 
547 #ifdef HAS_PERF_SUBSYSTEM
548  if (ReadInstructionCounter() >= instruction_limit_) {
549  return true;
550  }
551 #endif // HAS_PERF_SUBSYSTEM
552 
553  const int64 current_ns = absl::GetCurrentTimeNanos();
554  running_max_.Add(std::max(safety_buffer_ns_, current_ns - last_ns_));
555  last_ns_ = current_ns;
556  if (current_ns + running_max_.GetCurrentMax() >= limit_ns_) {
557  if (FLAGS_time_limit_use_usertime) {
558  // To avoid making many system calls, we only check the user time when
559  // the "absolute" time limit has been reached. Note that the user time
560  // should advance more slowly, so this is correct.
561  const double time_left_s = limit_in_seconds_ - user_timer_.Get();
562  if (time_left_s > kSafetyBufferSeconds) {
563  limit_ns_ = static_cast<int64>(time_left_s * 1e9) + last_ns_;
564  return false;
565  }
566  }
567 
568  // To ensure that future calls to LimitReached() will return true.
569  limit_ns_ = 0;
570  return true;
571  }
572  return false;
573 }
574 
575 inline double TimeLimit::GetTimeLeft() const {
576  if (limit_ns_ == kint64max) return std::numeric_limits<double>::infinity();
577  const int64 delta_ns = limit_ns_ - absl::GetCurrentTimeNanos();
578  if (delta_ns < 0) return 0.0;
579  if (FLAGS_time_limit_use_usertime) {
580  return std::max(limit_in_seconds_ - user_timer_.Get(), 0.0);
581  } else {
582  return delta_ns * 1e-9;
583  }
584 }
585 
587  return std::max(instruction_limit_ - ReadInstructionCounter(), 0.0);
588 }
589 
590 } // namespace operations_research
591 
592 #endif // OR_TOOLS_UTIL_TIME_LIMIT_H_
static std::unique_ptr< TimeLimit > Infinite()
Creates a time limit object that uses infinite time for wall time, deterministic time and instruction...
Definition: time_limit.h:134
double GetDeterministicTimeLeft() const
Returns the remaining deterministic time before LimitReached() returns true due to the deterministic ...
Definition: time_limit.h:212
void SetInstructionLimit(double instruction_limit)
Sets the instruction limit.
Definition: time_limit.h:171
~NestedTimeLimit()
Updates elapsed deterministic time in the base time limit object.
Definition: time_limit.h:340
double GetElapsedDeterministicTime() const
Definition: time_limit.h:385
std::string DebugString() const
Returns information about the time limit object in a human-readable form.
void MergeWithGlobalTimeLimit(TimeLimit *other)
Definition: time_limit.h:516
static const double kSafetyBufferSeconds
Definition: time_limit.h:107
double GetElapsedTime() const
Returns the time elapsed in seconds since the construction of this object.
Definition: time_limit.h:251
void AdvanceDeterministicTime(double deterministic_duration, const char *counter_name)
Advances the deterministic time.
Definition: time_limit.h:240
double GetInstructionsLeft()
Returns the number of instructions left to reach the limit.
Definition: time_limit.h:586
bool LimitReached() const
Definition: time_limit.h:358
void UpdateLocalLimit(TimeLimit *local_limit)
Definition: time_limit.h:370
static const int kHistorySize
Definition: time_limit.h:108
Definition: cp_model.h:52
~SharedTimeLimit()
Definition: time_limit.h:352
double GetElapsedDeterministicTime() const
Returns the elapsed deterministic time since the construction of this object.
Definition: time_limit.h:260
void AdvanceDeterministicTime(double deterministic_duration)
Advances the deterministic time.
Definition: time_limit.h:226
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
TimeLimit * GetTimeLimit()
Returns a time limit object that represents the combination of the overall time limit and the part-sp...
Definition: time_limit.h:462
TimeLimit()
Definition: time_limit.h:126
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:537
static std::unique_ptr< NestedTimeLimit > FromBaseTimeLimitAndParameters(TimeLimit *time_limit, const Parameters &parameters)
Creates a time limit object initialized from a base time limit and an object that provides methods ma...
Definition: time_limit.h:449
double GetTimeLeft() const
Returns the time left on this limit, or 0 if the limit was reached (it never returns a negative value...
Definition: time_limit.h:575
void Stop()
Definition: time_limit.h:365
double GetTimeLeft() const
Definition: time_limit.h:380
void ResetLimitFromParameters(const Parameters &parameters)
Sets new time limits.
Definition: time_limit.h:510
double ReadInstructionCounter()
Returns the number of instructions executed since the creation of this object.
Definition: time_limit.h:527
std::atomic< bool > * ExternalBooleanAsLimit() const
Returns the current external Boolean limit.
Definition: time_limit.h:282
void AdvanceDeterministicTime(double deterministic_duration)
Definition: time_limit.h:375
void RegisterExternalBooleanAsLimit(std::atomic< bool > *external_boolean_as_limit)
Registers the external Boolean to check when LimitReached() is called.
Definition: time_limit.h:274
SharedTimeLimit(TimeLimit *time_limit)
Definition: time_limit.h:342
static std::unique_ptr< TimeLimit > FromParameters(const Parameters &parameters)
Creates a time limit object initialized from an object that provides methods max_time_in_seconds() an...
Definition: time_limit.h:159
Provides a way to nest time limits for algorithms where a certain part of the computation is bounded ...
Definition: time_limit.h:427
TimeLimit & operator=(const TimeLimit &)=delete
NestedTimeLimit(TimeLimit *base_time_limit, double limit_in_seconds, double deterministic_limit)
Creates the nested time limit.
static std::unique_ptr< TimeLimit > FromDeterministicTime(double deterministic_limit)
Creates a time limit object that puts limit only on the deterministic time.
Definition: time_limit.h:144
friend class ParallelTimeLimit
Definition: time_limit.h:336
DECLARE_bool(time_limit_use_usertime)
Enables changing the behavior of the TimeLimit class to use -b usertime instead of walltime.