C++写node笔记(一)
by snoopyxdy
at 2012-11-23 22:33:33
original http://snoopyxdy.blog.163.com/blog/static/601174402012102391344617
binding.gyp文件:#include <node.h>
#include <v8.h>
using namespace v8;
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("world"));
}
void init(Handle<Object> target) {
target->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(hello, init)
接着执行{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}
var hello = require('./addon/build/Release/hello.node').hello();
console.log(hello); //这里打印world字符串
执行结果:node.js用时50毫秒console.time('for');
var j=0;
for(var i=0;i<10000000;i++){
j += i/2;
}
console.log(j)
console.timeEnd('for');
24999997500000
for: 50ms
node代码:#include <node.h>
#include <v8.h>
using namespace v8;
float forfunc(){
float i,j=0;
for(i=0;i<10000000;i++){
j += i/2;
};
return j;
}
void init(Handle<Object> target) {
float j;
j = forfunc();
target->Set(String::NewSymbol("hello"),Number::New(j));
}
NODE_MODULE(hello, init)
执行结果:C++模块执行速度26毫秒console.time('for');
var hello = require('./addon/build/Release/hello.node').hello;
console.log(hello)
console.timeEnd('for');
从测试我们看出,一些耗费CPU的密集型计算,利用C++模块可以把速度提升1倍。24999997500000
for: 26ms