I'm trying to write a function that measures the execution time of another function:
export class Profiler {
public measureSyncFunc(fn: () => any): Promise<number> {
return new Promise<number>((resolve, reject) => {
let elapsed = 0;
let intervalId = window.setInterval(() => {
elapsed += 1; // this is never called
}, 1);
this.execFunc(fn)
.then((result: any) => {
window.clearInterval(intervalId);
resolve(elapsed);
});
});
}
private execFunc(fn: () => any): Promise<any> {
return new Promise<any>((resolve, reject) => {
resolve(fn());
});
}
}
Then I use it like that:
let array = generateRandomArray(100000);
instance.measureSyncFunc(bubbleSort(array))
.then((elapsed: number) => {
console.log(`end session: ${elapsed} seconds`);
resolve();
});
The bubbleSort function is synchronous and it takes several seconds to complete. See code here:
The result in the console is "end session: 0 seconds" because the interval callback is never called.
Do you know how I can make it called ? Thank you very much guys !
=+
is an invalid operatorinstance.measureSyncFunc(bubbleSort(array))
you're passing the result of calling bubbleSort to yourmeasureSyncFunc
, butmeasureSyncFunc
expects a function as an argumentsetInterval
of 1ms - you can't actually get an interval that small - have you considered the profiling tools available in most browsers these days?performance.now()
orconsole.time('xxx') / console.timeEnd('xxx')
invalid operator
- actually, that would result inelapsed == 1
, permanently :p