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

前端 未结 10 1384
臣服心动
臣服心动 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:37

    Use the Node.js console.time() and console.timeEnd():

    var i;
    console.time("dbsave");
    
    for(i = 1; i < LIMIT; i++){
        db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
    }
    
    end = function(err, saved) {
        console.log(( err || !saved )?"Error":"Saved");
        if(--i === 1){console.timeEnd("dbsave");}
    };
    
    0 讨论(0)
  • 2020-11-30 16:38

    Invoking console.time('label') will record the current time in milliseconds, then later calling console.timeEnd('label') will display the duration from that point.

    The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label:

    console.time('test');
    //some code
    console.timeEnd('test'); //Prints something like that-> test: 11374.004ms
    

    For more information, see Mozilla's developer docs on console.time.

    0 讨论(0)
  • 2020-11-30 16:42

    You could also try exectimer. It gives you feedback like:

    var t = require("exectimer");
    
    var myFunction() {
       var tick = new t.tick("myFunction");
       tick.start();
       // do some processing and end this tick
       tick.stop();
    }
    
    // Display the results
    console.log(t.timers.myFunction.duration()); // total duration of all ticks
    console.log(t.timers.myFunction.min()); // minimal tick duration
    console.log(t.timers.myFunction.max()); // maximal tick duration
    console.log(t.timers.myFunction.mean()); // mean tick duration
    console.log(t.timers.myFunction.median()); // median tick duration
    

    [edit] There is even a simpler way now to use exectimer because now it can wrap the code to be measured. Your code could wrapped like this:

    var t = require('exectimer'),
    Tick = t.Tick;
    
    for(var i = 1; i < LIMIT; i++){
        Tick.wrap(function saveUsers(done) {
            db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
                if( err || !saved ) console.log("Error");
                else console.log("Saved");
                done();
            });
        });
    }
    
    // Display the results
    console.log(t.timers.myFunction.duration()); // total duration of all ticks
    console.log(t.timers.saveUsers.min()); // minimal tick duration
    console.log(t.timers.saveUsers.max()); // maximal tick duration
    console.log(t.timers.saveUsers.mean()); // mean tick duration
    console.log(t.timers.saveUsers.median()); // median tick duration
    
    0 讨论(0)
  • 2020-11-30 16:44
    var start = +new Date();
    var counter = 0;
    for(var i = 1; i < LIMIT; i++){
        ++counter;
        db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
              if( err || !saved ) console.log("Error");
              else console.log("Saved");
              if (--counter === 0) 
              {
                  var end = +new Date();
                  console.log("all users saved in " + (end-start) + " milliseconds");
              }
        });
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 16:54

    There is a method that is designed for this. Check out process.hrtime(); .

    So, I basically put this at the top of my app.

    var start = process.hrtime();
    
    var elapsed_time = function(note){
        var precision = 3; // 3 decimal places
        var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
        console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
        start = process.hrtime(); // reset the timer
    }
    

    Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":

    var debug = true;
    http.createServer(function(request, response) {
    
        if(debug) console.log("----------------------------------");
        if(debug) elapsed_time("recieved request");
    
        var send_html = function(err, contents) {
            if(debug) elapsed_time("start send_html()");
            response.writeHead(200, {'Content-Type': 'text/html' } );
            response.end(contents);
            if(debug) elapsed_time("end send_html()");
        }
    
        if(debug) elapsed_time("start readFile()");
        fs.readFile('output.txt', send_html);
        if(debug) elapsed_time("end readFile()");
    
    }).listen(8080);
    

    Here's a quick test you can run in a terminal (BASH shell):

    for i in {1..100}; do echo $i; curl http://localhost:8080/; done
    
    0 讨论(0)
提交回复
热议问题