ParallelismFactorCalculator.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. class ParallelismFactorCalculator {
  8. constructor() {
  9. this._rangePoints = [];
  10. this._rangeCallbacks = [];
  11. }
  12. range(start, end, callback) {
  13. if (start === end) return callback(1);
  14. this._rangePoints.push(start);
  15. this._rangePoints.push(end);
  16. this._rangeCallbacks.push(callback);
  17. }
  18. calculate() {
  19. const segments = Array.from(new Set(this._rangePoints)).sort((a, b) =>
  20. a < b ? -1 : 1
  21. );
  22. const parallelism = segments.map(() => 0);
  23. const rangeStartIndices = [];
  24. for (let i = 0; i < this._rangePoints.length; i += 2) {
  25. const start = this._rangePoints[i];
  26. const end = this._rangePoints[i + 1];
  27. let idx = binarySearchBounds.eq(segments, start);
  28. rangeStartIndices.push(idx);
  29. do {
  30. parallelism[idx]++;
  31. idx++;
  32. } while (segments[idx] < end);
  33. }
  34. for (let i = 0; i < this._rangeCallbacks.length; i++) {
  35. const start = this._rangePoints[i * 2];
  36. const end = this._rangePoints[i * 2 + 1];
  37. let idx = rangeStartIndices[i];
  38. let sum = 0;
  39. let totalDuration = 0;
  40. let current = start;
  41. do {
  42. const p = parallelism[idx];
  43. idx++;
  44. const duration = segments[idx] - current;
  45. totalDuration += duration;
  46. current = segments[idx];
  47. sum += p * duration;
  48. } while (current < end);
  49. this._rangeCallbacks[i](sum / totalDuration);
  50. }
  51. }
  52. }
  53. module.exports = ParallelismFactorCalculator;