如何检查 Node js 中的下载时间和执行?

How to check download time and execution in Node js?

我想检查每个文件的下载时间和所有文件的下载时间,如果下载速度慢或快,我们如何在节点js上查看和测量它?也可以考虑内存会更好。谢谢你。顺便说一句,下面代码中的 final_list 是一个 url 数组。

我的下载文件代码

var download = function (url, dest, callback) {

        request.get(url)
            .on('error', function (err) { console.log(err) })
            .pipe(fs.createWriteStream(dest))
            .on('close', callback);

    };

    final_list.forEach(function (str) {
        var filename = str.split('/').pop();

        console.log('Downloading ' + filename);

        download(str, filename, function () { console.log('Finished Downloading' + "" + filename) });
    });

计时方式:

  1. 使用process.hrtime.bigint()(高分辨率)。
  2. 使用console.time with console.timeEnd.

测量内存

使用process.memoryUsage().

这是使用上述所有方法更新的代码。

final_list.forEach(function (str) {
    var filename = str.split('/').pop();

    console.log('Downloading ' + filename);
    // console.time(filename);
    var start = process.hrtime.bigint();

    download(str, filename, function () {
        console.log('Finished Downloading' + "" + filename)
        // console.timeEnd(filename);
        var end = process.hrtime.bigint();
        var took = Number(end - start) / 1000000;
        console.log(`${filename}: ${took}ms`);
        console.log('Total used memory:', process.memoryUsage().heapUsed);
    });
});