壓力測試

Node.js 壓力測試

使用內建函式

// test performance function
const testPerformance = (testName, testFunction) => {
    const startTime = new Date().getTime();

    let i = 0;
    while (i < 10000000) {
        i++;
        testFunction();
    }

    const endTime = new Date().getTime();

    // jsonStringify 3698 ms
    console.log(testName, endTime - startTime, 'ms');
};

// 執行測試
testPerformance('jsonStringify', jsonStringify);

// 要測試的功能
function jsonStringify() {
    JSON.stringify({ foo: 'name' });
}
let start;
let end;

start = new Date();

// Do something here
for (var i = 0; i < 1000; i++) {
    Math.sqrt(i);
}

end = new Date();

// Operation took 0 ms
console.log('Operation took ' + (end.getTime() - start.getTime()) + ' ms');

使用 chrome devtool 的函式

const timeTaken = (callback) => {
  console.time('timer');
  const r = callback();
  console.timeEnd('timer');
  return r;
};

timeTaken(() => {
  // Do something here
  for (var i = 0; i < 1000; i++) {
    Math.sqrt(i);
  }
});

參考資料