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/time/clock.h"
27 #include "ortools/base/commandlineflags.h"
28 #include "ortools/base/logging.h"
29 #include "ortools/base/macros.h"
30 #include "ortools/base/timer.h"
31 #include "ortools/util/running_stat.h"
32 #ifdef HAS_PERF_SUBSYSTEM
33 #include "exegesis/exegesis/itineraries/perf_subsystem.h"
34 #endif // HAS_PERF_SUBSYSTEM
35 
40 DECLARE_bool(time_limit_use_usertime);
41 
46 DECLARE_bool(time_limit_use_instruction_count);
47 
48 namespace operations_research {
49 
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 
370  public:
375  NestedTimeLimit(TimeLimit* base_time_limit, double limit_in_seconds,
376  double deterministic_limit);
377 
382 
390  template <typename Parameters>
391  static std::unique_ptr<NestedTimeLimit> FromBaseTimeLimitAndParameters(
392  TimeLimit* time_limit, const Parameters& parameters) {
393  return absl::make_unique<NestedTimeLimit>(
394  time_limit, parameters.max_time_in_seconds(),
395  parameters.max_deterministic_time());
396  }
397 
404  TimeLimit* GetTimeLimit() { return &time_limit_; }
405 
406  private:
407  TimeLimit* const base_time_limit_;
408  TimeLimit time_limit_;
409 
410  DISALLOW_COPY_AND_ASSIGN(NestedTimeLimit);
411 };
412 
413 // ################## Implementations below #####################
414 
415 inline TimeLimit::TimeLimit(double limit_in_seconds, double deterministic_limit,
416  double instruction_limit)
417  : safety_buffer_ns_(static_cast<int64>(kSafetyBufferSeconds * 1e9)),
418  running_max_(kHistorySize),
419  external_boolean_as_limit_(nullptr) {
420  ResetTimers(limit_in_seconds, deterministic_limit, instruction_limit);
421 }
422 
423 inline void TimeLimit::ResetTimers(double limit_in_seconds,
424  double deterministic_limit,
425  double instruction_limit) {
426  if (external_boolean_as_limit_ != nullptr) {
427  *external_boolean_as_limit_ = false;
428  }
429  elapsed_deterministic_time_ = 0.0;
430  deterministic_limit_ = deterministic_limit;
431  instruction_limit_ = instruction_limit;
432 
433  if (FLAGS_time_limit_use_usertime) {
434  user_timer_.Start();
435  limit_in_seconds_ = limit_in_seconds;
436  }
437 #ifdef HAS_PERF_SUBSYSTEM
438  if (FLAGS_time_limit_use_instruction_count) {
439  perf_subsystem_.CleanUp();
440  perf_subsystem_.AddEvent(GetInstructionRetiredEventName());
441  perf_subsystem_.StartCollecting();
442  }
443 #endif // HAS_PERF_SUBSYSTEM
444  start_ns_ = absl::GetCurrentTimeNanos();
445  last_ns_ = start_ns_;
446  limit_ns_ = limit_in_seconds >= 1e-9 * (kint64max - start_ns_)
447  ? kint64max
448  : static_cast<int64>(limit_in_seconds * 1e9) + start_ns_;
449 }
450 
451 template <typename Parameters>
452 inline void TimeLimit::ResetLimitFromParameters(const Parameters& parameters) {
453  ResetTimers(parameters.max_time_in_seconds(),
454  parameters.max_deterministic_time(),
455  std::numeric_limits<double>::infinity());
456 }
457 
459  if (other == nullptr) return;
460  ResetTimers(
461  std::min(GetTimeLeft(), other->GetTimeLeft()),
463  std::numeric_limits<double>::infinity());
464  if (other->ExternalBooleanAsLimit() != nullptr) {
466  }
467 }
468 
470 #ifdef HAS_PERF_SUBSYSTEM
471  if (FLAGS_time_limit_use_instruction_count) {
472  return perf_subsystem_.ReadCounters().GetScaledOrDie(
473  GetInstructionRetiredEventName());
474  }
475 #endif // HAS_PERF_SUBSYSTEM
476  return 0;
477 }
478 
479 inline bool TimeLimit::LimitReached() {
480  if (external_boolean_as_limit_ != nullptr &&
481  external_boolean_as_limit_->load()) {
482  return true;
483  }
484 
485  if (GetDeterministicTimeLeft() <= 0.0) {
486  return true;
487  }
488 
489 #ifdef HAS_PERF_SUBSYSTEM
490  if (ReadInstructionCounter() >= instruction_limit_) {
491  return true;
492  }
493 #endif // HAS_PERF_SUBSYSTEM
494 
495  const int64 current_ns = absl::GetCurrentTimeNanos();
496  running_max_.Add(std::max(safety_buffer_ns_, current_ns - last_ns_));
497  last_ns_ = current_ns;
498  if (current_ns + running_max_.GetCurrentMax() >= limit_ns_) {
499  if (FLAGS_time_limit_use_usertime) {
500  // To avoid making many system calls, we only check the user time when
501  // the "absolute" time limit has been reached. Note that the user time
502  // should advance more slowly, so this is correct.
503  const double time_left_s = limit_in_seconds_ - user_timer_.Get();
504  if (time_left_s > kSafetyBufferSeconds) {
505  limit_ns_ = static_cast<int64>(time_left_s * 1e9) + last_ns_;
506  return false;
507  }
508  }
509 
510  // To ensure that future calls to LimitReached() will return true.
511  limit_ns_ = 0;
512  return true;
513  }
514  return false;
515 }
516 
517 inline double TimeLimit::GetTimeLeft() const {
518  if (limit_ns_ == kint64max) return std::numeric_limits<double>::infinity();
519  const int64 delta_ns = limit_ns_ - absl::GetCurrentTimeNanos();
520  if (delta_ns < 0) return 0.0;
521  if (FLAGS_time_limit_use_usertime) {
522  return std::max(limit_in_seconds_ - user_timer_.Get(), 0.0);
523  } else {
524  return delta_ns * 1e-9;
525  }
526 }
527 
529  return std::max(instruction_limit_ - ReadInstructionCounter(), 0.0);
530 }
531 
532 } // namespace operations_research
533 
534 #endif // OR_TOOLS_UTIL_TIME_LIMIT_H_
void RegisterExternalBooleanAsLimit(std::atomic< bool > *external_boolean_as_limit)
Registers the external Boolean to check when LimitReached() is called.
Definition: time_limit.h:274
static const double kSafetyBufferSeconds
Definition: time_limit.h:107
double ReadInstructionCounter()
Returns the number of instructions executed since the creation of this object.
Definition: time_limit.h:469
NestedTimeLimit(TimeLimit *base_time_limit, double limit_in_seconds, double deterministic_limit)
Creates the nested time limit.
double GetElapsedDeterministicTime() const
Returns the elapsed deterministic time since the construction of this object.
Definition: time_limit.h:260
double GetInstructionsLeft()
Returns the number of instructions left to reach the limit.
Definition: time_limit.h:528
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:479
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 GetElapsedTime() const
Returns the time elapsed in seconds since the construction of this object.
Definition: time_limit.h:251
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
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:517
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
void AdvanceDeterministicTime(double deterministic_duration, const char *counter_name)
Advances the deterministic time.
Definition: time_limit.h:240
std::atomic< bool > * ExternalBooleanAsLimit() const
Returns the current external Boolean limit.
Definition: time_limit.h:282
TimeLimit * GetTimeLimit()
Returns a time limit object that represents the combination of the overall time limit and the part-sp...
Definition: time_limit.h:404
DECLARE_bool(time_limit_use_usertime)
Enables changing the behavior of the TimeLimit class to use -b usertime instead of walltime.
TimeLimit & operator=(const TimeLimit &)=delete
void SetInstructionLimit(double instruction_limit)
Sets the instruction limit.
Definition: time_limit.h:171
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
Provides a way to nest time limits for algorithms where a certain part of the computation is bounded ...
Definition: time_limit.h:369
void ResetLimitFromParameters(const Parameters &parameters)
Sets new time limits.
Definition: time_limit.h:452
static const int kHistorySize
Definition: time_limit.h:108
std::string DebugString() const
Returns information about the time limit object in a human-readable form.
void AdvanceDeterministicTime(double deterministic_duration)
Advances the deterministic time.
Definition: time_limit.h:226
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:391
double GetDeterministicTimeLeft() const
Returns the remaining deterministic time before LimitReached() returns true due to the deterministic ...
Definition: time_limit.h:212
~NestedTimeLimit()
Updates elapsed deterministic time in the base time limit object.
void MergeWithGlobalTimeLimit(TimeLimit *other)
Definition: time_limit.h:458