简体   繁体   中英

How to measure import execution time

How can I measure execution time of import without stepping inside it?

Let say I have code bellow.


main.js

const now = Date.now();
import './module';
console.log(`${Date.now() - now}ms`);
// shows 0ms

module.js

const now = Date.now();
let a = 0;
for(let i = 0; i < 1000 * 1000 * 1000, i++) a++;
console.log(`${Date.now() - now}ms`;
// shows 1000ms

Your main.js doesn't work because no code of the module is executed until all imported dependencies have been loaded and initialised (executed). The two Date.now() calls will always run immediately after each other, resulting in the output of 0ms.

You would need to load another module before the measured module.js to take the start time:

// main.js
import { now as start } from 'beginMeasure';
import './module';
const end = Date.now();
console.log(`${end - start}ms`);
// beginMeasure.js
export const now = Date.now();

The best way I found to measure imported module execution time, is using require instead. It is good to determine slow modules and revert back to import.

const now = Date.now();
const module1 = require('./module1');
console.log(`module1: ${Date.now() - now}ms`);
const module2 = require('./module2');
console.log(`module2: ${Date.now() - now}ms`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM