How do I measure the execution time of JavaScript code with callbacks?

前端 未结 10 1514
臣服心动
臣服心动 2020-11-30 16:28

I have a piece of JavaScript code that I am executing using the node.js interpreter.

for(var i = 1; i <         


        
10条回答
  •  一个人的身影
    2020-11-30 16:48

    Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime) internally.

    var perfy = require('perfy');
    
    function end(label) {
        return function (err, saved) {
            console.log(err ? 'Error' : 'Saved'); 
            console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
        };
    }
    
    for (var i = 1; i < LIMIT; i++) {
        var label = 'db-save-' + i;
        perfy.start(label); // <——— start and mark time
        db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
    }
    

    Note that each time perfy.end(label) is called, that instance is auto-destroyed.

    Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.

提交回复
热议问题