SliceBudget.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef js_SliceBudget_h
  6. #define js_SliceBudget_h
  7. #include <stdint.h>
  8. namespace js {
  9. struct JS_PUBLIC_API(TimeBudget)
  10. {
  11. int64_t budget;
  12. explicit TimeBudget(int64_t milliseconds) { budget = milliseconds; }
  13. };
  14. struct JS_PUBLIC_API(WorkBudget)
  15. {
  16. int64_t budget;
  17. explicit WorkBudget(int64_t work) { budget = work; }
  18. };
  19. /*
  20. * This class records how much work has been done in a given collection slice,
  21. * so that we can return before pausing for too long. Some slices are allowed
  22. * to run for unlimited time, and others are bounded. To reduce the number of
  23. * gettimeofday calls, we only check the time every 1000 operations.
  24. */
  25. class JS_PUBLIC_API(SliceBudget)
  26. {
  27. static const int64_t unlimitedDeadline = INT64_MAX;
  28. static const intptr_t unlimitedStartCounter = INTPTR_MAX;
  29. bool checkOverBudget();
  30. SliceBudget();
  31. public:
  32. // Memory of the originally requested budget. If isUnlimited, neither of
  33. // these are in use. If deadline==0, then workBudget is valid. Otherwise
  34. // timeBudget is valid.
  35. TimeBudget timeBudget;
  36. WorkBudget workBudget;
  37. int64_t deadline; /* in microseconds */
  38. intptr_t counter;
  39. static const intptr_t CounterReset = 1000;
  40. static const int64_t UnlimitedTimeBudget = -1;
  41. static const int64_t UnlimitedWorkBudget = -1;
  42. /* Use to create an unlimited budget. */
  43. static SliceBudget unlimited() { return SliceBudget(); }
  44. /* Instantiate as SliceBudget(TimeBudget(n)). */
  45. explicit SliceBudget(TimeBudget time);
  46. /* Instantiate as SliceBudget(WorkBudget(n)). */
  47. explicit SliceBudget(WorkBudget work);
  48. void makeUnlimited() {
  49. deadline = unlimitedDeadline;
  50. counter = unlimitedStartCounter;
  51. }
  52. void step(intptr_t amt = 1) {
  53. counter -= amt;
  54. }
  55. bool isOverBudget() {
  56. if (counter > 0)
  57. return false;
  58. return checkOverBudget();
  59. }
  60. bool isWorkBudget() const { return deadline == 0; }
  61. bool isTimeBudget() const { return deadline > 0 && !isUnlimited(); }
  62. bool isUnlimited() const { return deadline == unlimitedDeadline; }
  63. int describe(char* buffer, size_t maxlen) const;
  64. };
  65. } // namespace js
  66. #endif /* js_SliceBudget_h */