zappyzep/backend/src/utils/easyProfiler.ts

51 lines
1.1 KiB
TypeScript
Raw Normal View History

import { Profiler } from "knub/dist/Profiler";
import { performance } from "perf_hooks";
2021-10-28 17:11:56 +03:00
import { SECONDS, noop } from "../utils";
let _profilingEnabled = false;
export const profilingEnabled = () => {
return _profilingEnabled;
};
export const enableProfiling = () => {
_profilingEnabled = true;
};
export const disableProfiling = () => {
_profilingEnabled = false;
};
export const startProfiling = (profiler: Profiler, key: string) => {
2021-10-28 17:11:56 +03:00
if (!profilingEnabled()) {
return noop;
}
const startTime = performance.now();
return () => {
profiler.addDataPoint(key, performance.now() - startTime);
};
};
2021-10-05 23:54:52 +03:00
export const calculateBlocking = (coarseness = 10) => {
2021-10-28 17:11:56 +03:00
if (!profilingEnabled()) {
return () => 0;
}
2021-10-05 23:54:52 +03:00
let last = performance.now();
let result = 0;
const interval = setInterval(() => {
const now = performance.now();
const blockedTime = Math.max(0, now - last - coarseness);
result += blockedTime;
last = now;
}, coarseness);
setTimeout(() => clearInterval(interval), 10 * SECONDS);
return () => {
clearInterval(interval);
return result;
};
};