比较nodejs c++插件的速度和js等效的速度

Comparing nodejs c++ addon's speed with js equivalent?

本文关键字:速度 js nodejs 插件 比较 c++      更新时间:2023-09-26

我有一个nodejs程序,我在其中做了很多计算。我正在考虑让它更快,所以我决定尝试将一些代码移动到 c++。但首先,我执行了一个快速测试,以查看性能提升是否显着。

我知道在 v8 中调用 c++ 函数很昂贵,所以在我的测试中只有一次调用!

binding.gyp 文件:

{
  "targets": [
    {
      "target_name": "test",
      "sources": [ "test.cc" ]
    }
  ]
}

test.cc 文件:

#include <node.h>
#include <v8.h>
#include <cstdlib>
#include <time.h>
using namespace v8;
Handle<Value> Func(const Arguments& args) {
  HandleScope scope;
  double sum = 0;
  double x = rand() / RAND_MAX;
  double y = rand() / RAND_MAX;
  for (int i = 0; i < 1e9; i += 1) {
    x = x / y;
    y = x * rand() / RAND_MAX;
    sum += x + y;
  }
  return scope.Close(Number::New(sum));
}
void init(Handle<Object> exports) {
  srand(time(NULL));
  exports->Set(String::NewSymbol("func"),
      FunctionTemplate::New(Func)->GetFunction());
}
NODE_MODULE(test, init)

测试.js文件:

'use strict';
var cpp = require("./build/Release/test").func;
function js() {
  var sum = 0;
  var x = Math.random();
  var y = Math.random();
  for (var i = 0; i < 1e9; i += 1) {
    x = x / y;
    y = x * Math.random();
    sum += x + y;
  }
  return sum;
}
function log(msg, hrtime) {
  console.log(msg, (hrtime[0] * 1e9 + hrtime[1]) * 1e-9);
}
var t = process.hrtime();
js();
log('JS', process.hrtime(t));
t = process.hrtime();
cpp();
log('CPP', process.hrtime(t));

结果:

JS 8.060747399 
CPP 15.041201326000001

为什么 c++ 插件这么慢?

我正在使用节点 v0.10.21

div 操作是最昂贵的,与 js 代码相比,您使用它的次数多了 3 次。另外,你不知道random()是如何实现的。来自 c++ 的random()代码可能与来自 js 的random()代码有很大不同,所以不要做假设。

"在 C++ 中写入性能敏感部分"的想法在 V8 中存在缺陷。这在python/php中是有意义的,其中规范解释器实际上比V8编译的javascript慢10000x+。

如果你在编写JS时考虑到性能,你很容易达到足够快的水平。尽管编写这样的JS并不容易,因为几乎每个直观的习语都不利于性能。