如何计算Nodejs中的执行时间ChildProcess.exec

时间:2017-03-31 14:42:09

标签: javascript node.js parameters execution-time

我们有一个API请求可以登录我们的用户,如下所示:

...

//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 ?

      }

    });

});
...

我看到打印的执行时间不正确,因为当许多用户同时登录时,用于计算executionTime的“t0”值(“Date.now() - t0”)未正确计算。它使用此API请求的最近调用的t0值,而不是相应的t0值。

这是因为exec方法是异步的,需要时间来执行。

如何正确处理原始t0变量丢失的执行时间(“Date.now() - t0”)?

1 个答案:

答案 0 :(得分:0)

我只需要把

var t0 = Date.now();

它有效!