performance-monitor.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * Adapted from LiteMol
  5. * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
  6. */
  7. import { now } from 'mol-task/util/now'
  8. export class PerformanceMonitor {
  9. private starts = new Map<string, number>();
  10. private ends = new Map<string, number>();
  11. static currentTime() {
  12. return now();
  13. }
  14. start(name: string) {
  15. this.starts.set(name, now());
  16. }
  17. end(name: string) {
  18. this.ends.set(name, now());
  19. }
  20. static format(t: number) {
  21. if (isNaN(t)) return 'n/a';
  22. let h = Math.floor(t / (60 * 60 * 1000)),
  23. m = Math.floor(t / (60 * 1000) % 60),
  24. s = Math.floor(t / 1000 % 60),
  25. ms = Math.floor(t % 1000).toString();
  26. while (ms.length < 3) ms = '0' + ms;
  27. if (h > 0) return `${h}h${m}m${s}.${ms}s`;
  28. if (m > 0) return `${m}m${s}.${ms}s`;
  29. if (s > 0) return `${s}.${ms}s`;
  30. return `${t.toFixed(0)}ms`;
  31. }
  32. formatTime(name: string) {
  33. return PerformanceMonitor.format(this.time(name));
  34. }
  35. formatTimeSum(...names: string[]) {
  36. return PerformanceMonitor.format(this.timeSum(...names));
  37. }
  38. /** Returns the time in milliseconds and removes them from the cache. */
  39. time(name: string): number {
  40. let start = this.starts.get(name)!, end = this.ends.get(name)!;
  41. this.starts.delete(name);
  42. this.ends.delete(name);
  43. return end - start;
  44. }
  45. timeSum(...names: string[]) {
  46. let t = 0;
  47. for (let m of names.map(n => this.ends.get(n)! - this.starts.get(n)!)) t += m;
  48. return t;
  49. }
  50. }