简体   繁体   中英

How to compute execution time in Nodejs ChildProcess.exec

We have an API request that logins our users, like this:

...

//lauches an API request

router.post("/trip/analyse",function(req,res){

    t0 = Date.now();

    shell = ("sudo /usr/bin/python /mypythonFile");

    child = exec(shell, function (error, stdout, stderr) {

      if (error) { //There is an error

        res.json({"Error" : true});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }else{ //everything went fine

        res.json({"Error" : false});

        console.log(Date.now() - t0);  // <-------- HERE, How to get this right ?

      }

    });

});
...

I see that the printed execution time is not right, because when many users login at the same time, the "t0" value used for computing the executionTime ("Date.now() - t0") is not correctly computed. It uses the t0 values of a more recent call of this API request, and not the appropriate t0 value.

This is because the exec method is asynchronous and take time to execute.

How do I right properly the execution time ("Date.now() - t0"), where the original t0 variable is lost ?

I only had to put

var t0 = Date.now();

And it worked !

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