简体   繁体   English

对引发错误的异步代码和同步代码进行基准测试

[英]Benchmarking asynchronous vs synchronous code that throws an error

I have two functions; 我有两个功能; one is async ( testAsync ) and one is sync ( testSync ). 一个是异步( testAsync ),一个是同步( testSync )。 I'm trying to use them with benchmark.js. 我正在尝试将它们与benchmark.js一起使用。 Which one is faster and by how much. 哪一个更快,多少。 They should both throw an error. 他们都应该抛出错误。

I'm confused how I'm supposed to a) setup an asynchronous test b) make sure the test accounts throw an error for each function. 我很困惑我应该如何a)设置异步测试b)确保测试帐户为每个函数抛出一个错误。

Here's what I got: 这是我得到的:

import Benchmark from 'benchmark'
var suite = new Benchmark.Suite;

// add tests
suite.add('query validation test sync', function(deferred) {
  try {
    testSync({'name': 'reggi'});
  } catch (e) {
    deferred.resolve();
  }
})
.add('query validation test async', function(deferred) {
  testAsync({'name': 'reggi'}, {})
    .then(deferred.resolve)
    .catch(deferred.resolve);
})
// add listeners
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('error', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });

You should specify defer: true as option the test function: 你应该指定defer: true作为测试函数的选项:

suite.add('query validation test sync', function() {
  try {
    testSync({'name': 'reggi'});
  } catch (e) {
    // it's sync code, you don't need use defer here
  }
})
.add('query validation test async', {
  defer: true,
  fn: function(deferred) {
    testAsync({'name': 'reggi'}, {})
      .then(deferred.resolve)
      .catch(deferred.resolve);
  }
})
...

Check example on the benchmark.js site (in the middle of section) 检查 benchmark.js站点上的示例(在部分中间)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM