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

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

提交回复
热议问题