timing.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const assert = require('assert');
  3. const MAP = Symbol('Timing#map');
  4. const LIST = Symbol('Timing#list');
  5. class Timing {
  6. constructor() {
  7. this._enable = true;
  8. this[MAP] = new Map();
  9. this[LIST] = [];
  10. this.init();
  11. }
  12. init() {
  13. // process start time
  14. this.start('Process Start', Date.now() - Math.floor((process.uptime() * 1000)));
  15. this.end('Process Start');
  16. if (typeof process.scriptStartTime === 'number') {
  17. // js script start execute time
  18. this.start('Script Start', process.scriptStartTime);
  19. this.end('Script Start');
  20. }
  21. }
  22. start(name, start) {
  23. if (!name || !this._enable) return;
  24. if (this[MAP].has(name)) this.end(name);
  25. start = start || Date.now();
  26. const item = {
  27. name,
  28. start,
  29. end: undefined,
  30. duration: undefined,
  31. pid: process.pid,
  32. index: this[LIST].length,
  33. };
  34. this[MAP].set(name, item);
  35. this[LIST].push(item);
  36. return item;
  37. }
  38. end(name) {
  39. if (!name || !this._enable) return;
  40. assert(this[MAP].has(name), `should run timing.start('${name}') first`);
  41. const item = this[MAP].get(name);
  42. item.end = Date.now();
  43. item.duration = item.end - item.start;
  44. return item;
  45. }
  46. enable() {
  47. this._enable = true;
  48. }
  49. disable() {
  50. this._enable = false;
  51. }
  52. clear() {
  53. this[MAP].clear();
  54. this[LIST] = [];
  55. }
  56. toJSON() {
  57. return this[LIST];
  58. }
  59. }
  60. module.exports = Timing;