ParallelismFactorCalculator.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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("../util/binarySearchBounds");
  7. /** @typedef {function(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 = Array.from(new Set(this._rangePoints)).sort((a, b) =>
  29. a < b ? -1 : 1
  30. );
  31. const parallelism = segments.map(() => 0);
  32. const rangeStartIndices = [];
  33. for (let i = 0; i < this._rangePoints.length; i += 2) {
  34. const start = this._rangePoints[i];
  35. const end = this._rangePoints[i + 1];
  36. let idx = binarySearchBounds.eq(segments, start);
  37. rangeStartIndices.push(idx);
  38. do {
  39. parallelism[idx]++;
  40. idx++;
  41. } while (segments[idx] < end);
  42. }
  43. for (let i = 0; i < this._rangeCallbacks.length; i++) {
  44. const start = this._rangePoints[i * 2];
  45. const end = this._rangePoints[i * 2 + 1];
  46. let idx = rangeStartIndices[i];
  47. let sum = 0;
  48. let totalDuration = 0;
  49. let current = start;
  50. do {
  51. const p = parallelism[idx];
  52. idx++;
  53. const duration = segments[idx] - current;
  54. totalDuration += duration;
  55. current = segments[idx];
  56. sum += p * duration;
  57. } while (current < end);
  58. this._rangeCallbacks[i](sum / totalDuration);
  59. }
  60. }
  61. }
  62. module.exports = ParallelismFactorCalculator;