ParallelismFactorCalculator.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const binarySearchBounds = require("./binarySearchBounds");
  7. /** @typedef {(value: number) => void} Callback */
  8. class ParallelismFactorCalculator {
  9. constructor() {
  10. /** @type {number[]} */
  11. this._rangePoints = [];
  12. /** @type {Callback[]} */
  13. this._rangeCallbacks = [];
  14. }
  15. /**
  16. * @param {number} start range start
  17. * @param {number} end range end
  18. * @param {Callback} callback callback
  19. * @returns {void}
  20. */
  21. range(start, end, callback) {
  22. if (start === end) return callback(1);
  23. this._rangePoints.push(start);
  24. this._rangePoints.push(end);
  25. this._rangeCallbacks.push(callback);
  26. }
  27. calculate() {
  28. const segments = [...new Set(this._rangePoints)].sort((a, b) =>
  29. a < b ? -1 : 1
  30. );
  31. const parallelism = segments.map(() => 0);
  32. /** @type {number[]} */
  33. const rangeStartIndices = [];
  34. for (let i = 0; i < this._rangePoints.length; i += 2) {
  35. const start = this._rangePoints[i];
  36. const end = this._rangePoints[i + 1];
  37. let idx = binarySearchBounds.eq(segments, start);
  38. rangeStartIndices.push(idx);
  39. do {
  40. parallelism[idx]++;
  41. idx++;
  42. } while (segments[idx] < end);
  43. }
  44. for (let i = 0; i < this._rangeCallbacks.length; i++) {
  45. const start = this._rangePoints[i * 2];
  46. const end = this._rangePoints[i * 2 + 1];
  47. let idx = rangeStartIndices[i];
  48. let sum = 0;
  49. let totalDuration = 0;
  50. let current = start;
  51. do {
  52. const p = parallelism[idx];
  53. idx++;
  54. const duration = segments[idx] - current;
  55. totalDuration += duration;
  56. current = segments[idx];
  57. sum += p * duration;
  58. } while (current < end);
  59. this._rangeCallbacks[i](sum / totalDuration);
  60. }
  61. }
  62. }
  63. module.exports = ParallelismFactorCalculator;