How to get a microtime in Node.js?

后端 未结 13 1187
情深已故
情深已故 2020-12-04 13:41

How can I get the most accurate time stamp in Node.js?

ps My version of Node.js is 0.8.X and the node-microtime extension doesn\'t work for me (crash on install)

13条回答
  •  天命终不由人
    2020-12-04 14:25

    now('milli'); //  120335360.999686
    now('micro') ; // 120335360966.583
    now('nano') ; //  120335360904333
    

    Known that now is :

    const now = (unit) => {
    
      const hrTime = process.hrtime();
    
      switch (unit) {
    
        case 'milli':
          return hrTime[0] * 1000 + hrTime[1] / 1000000;
    
        case 'micro':
          return hrTime[0] * 1000000 + hrTime[1] / 1000;
    
        case 'nano':
          return hrTime[0] * 1000000000 + hrTime[1];
    
        default:
          return now('nano');
      }
    
    };
    

提交回复
热议问题