我正在尝试编写一个函数来测量另一个函数的执行时间:
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());
});
}
}
然后我像这样使用它:
let array = generateRandomArray(100000);
instance.measureSyncFunc(bubbleSort(array))
.then((elapsed: number) => {
console.log(`end session: ${elapsed} seconds`);
resolve();
});
气泡排序功能是同步的,需要几秒钟才能完成。请参阅此处的代码:
控制台中的结果是“结束会话:0 秒”,因为从不调用间隔回调。
你知道我怎么称呼它吗?非常感谢你们 !