编写c++代码
// demo.cc
#include <node.h>
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;
using v8::Number;
double Sum(){
int i;
double a = 3.1415926,b = 2.718;
for(i = 0;i<1000000000;i++){
a+=b;
}
return a;
}
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
double a = Sum();
auto total = Number::New(isolate , a);
args.GetReturnValue().Set(total);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "sum", Method);
}
NODE_MODULE(addon, init)
编写配置文件
{
"targets": [
{
"target_name": "addon",
"sources": [ "demo.cc" ]
}
]
}
编译
node-gyp configure build##
js引入执行
let addon = require('./build/Release/addon')
function Sum(){
let a = 3.1415926
let b = 2.718;
for(let i = 0;i<1000000000;i++){
a+=b;
}
return a;
}
console.time("C++")
console.log(addon.sum())
console.timeEnd("C++")
console.time('JS')
console.log(Sum())
console.timeEnd('JS')
分析
以上代码是将a循环加上b,循环十亿次
看一下输出结果不同机器结果可能不同,但整体差距大致相同
此处c++耗时972.209ms 1s = 1000ms
js耗时13637.128ms