units.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. export function relativeChange(final: number, initial: number): number {
  2. return (final - initial) / initial;
  3. }
  4. export type ProfilingFormatterUnit =
  5. | 'nanoseconds'
  6. | 'microseconds'
  7. | 'milliseconds'
  8. | 'seconds';
  9. const durationMappings: Record<ProfilingFormatterUnit, number> = {
  10. nanoseconds: 1e-9,
  11. microseconds: 1e-6,
  12. milliseconds: 1e-3,
  13. seconds: 1,
  14. };
  15. export function formatTo(
  16. v: number,
  17. from: ProfilingFormatterUnit | string,
  18. to: ProfilingFormatterUnit | string
  19. ) {
  20. const fromMultiplier = Math.log10(durationMappings[from]);
  21. const toMultiplier = Math.log10(durationMappings[to]);
  22. const value = v * Math.pow(10, fromMultiplier - toMultiplier);
  23. return value;
  24. }
  25. const format = (v: number, abbrev: string, precision: number) => {
  26. return v.toFixed(precision) + abbrev;
  27. };
  28. export function makeFormatter(
  29. from: ProfilingFormatterUnit | string
  30. ): (value: number) => string {
  31. const multiplier = durationMappings[from];
  32. if (multiplier === undefined) {
  33. throw new Error(`Cannot format unit ${from}, duration mapping is not defined`);
  34. }
  35. return (value: number) => {
  36. const duration = value * multiplier;
  37. if (duration >= 1) {
  38. return format(duration, 's', 2);
  39. }
  40. if (duration / 1e-3 >= 1) {
  41. return format(duration / 1e-3, 'ms', 2);
  42. }
  43. if (duration / 1e-6 >= 1) {
  44. return format(duration / 1e-6, 'μs', 2);
  45. }
  46. return format(duration / 1e-9, 'ns', 2);
  47. };
  48. }
  49. function pad(n: number, slots: number) {
  50. return Math.floor(n).toString().padStart(slots, '0');
  51. }
  52. export function makeTimelineFormatter(from: ProfilingFormatterUnit | string) {
  53. const multiplier = durationMappings[from];
  54. if (multiplier === undefined) {
  55. throw new Error(`Cannot format unit ${from}, duration mapping is not defined`);
  56. }
  57. return (value: number) => {
  58. const s = value * multiplier;
  59. const m = s / 60;
  60. const ms = s * 1e3;
  61. return `${pad(m, 2)}:${pad(s % 60, 2)}.${pad(ms % 1e3, 3)}`;
  62. };
  63. }