duration-interval-clock
v1.0.5
Published
A small library to measure duration and interval, including averaging.
Downloads
137
Maintainers
Readme
duration-interval-clock
github, npm
A small library to measure the duration and interval of execution, including averaging.
Measures time between start()
and end()
to provide duration, and between end()
and the subsequent end()
to provide interval, both with built-in window-averaging.
Usage
Simple usage:
import { DurationIntervalClock } from 'duration-interval-clock';
// defaults to average over 10 last measurements
const dic = new DurationIntervalClock();
dic.start();
// perform some task
dic.end();
// number of milliseconds taken by the task
dic.lastDuration
// average, after one measurement will be equal to lastDuration
dic.averageDuration
// both will be undefined, start() needs to be called at least twice
dic.lastInterval, dic.averageInterval
Example:
import { DurationIntervalClock } from 'duration-interval-clock';
// average over last 5 measurements
const dic = new DurationIntervalClock(5);
for(let i = 0; i <= 20; i++) {
const ret = await dic.measureAsync(async () => {
// some async task
await new Promise(r => setTimeout(r, 100 + i * 10));
return "ret value";
});
new Promise(r => setTimeout(r, 50));
if(i % 5 === 0) {
console.log("\nIteration", i)
console.log(" lastDuration:", dic.lastDuration);
console.log(" averageDuration:", dic.averageDuration);
console.log(" lastInterval:", dic.lastInterval);
console.log(" averageInterval:", dic.averageInterval);
}
}
Types:
class DurationIntervalClock {
sampleTargetCount: number;
durationsSamples: number[];
intervalSamples: number[];
constructor(sampleTargetCount?: number = 10);
reset(): void;
cancel(ignoreIfNotStarted?: boolean = false): void; // cancel last start()
start(endIfAlreadyStarted?: boolean = false): void;
// itemsProcessed may be a positive number which will divide measured values
end(ignoreIfNotStarted?: boolean = false, itemsProcessed?: number): void;
measureAsync<T>(fn: () => Promise<T>): Promise<T>;
measureSync<T>(fn: () => T): T;
checkHasGoodAverage(q?: number = 0.5): boolean;
get isStarted(): boolean;
get lastDuration(): number | undefined;
get lastInterval(): number | undefined;
get averageDuration(): number | undefined;
get averageInterval(): number | undefined;
}
FAQ
1. What is interval and duration?
Last interval measures end()-to-end(), last duration measures subsequent start()-to-end().