NODE / NODE C++ / NODE C++ INLINE ASM 性能大测试!
目标:斐波那契数列 前30位 循环100万次
位数多了,大数的话,JS还是C代码写起来很麻烦,嗯,更别说汇编了
代码:
function jstest(){
var time = new Date();
var a,b,res;
for(var t =0;t<1000000;t++) {
a = 0;
b = 1;
for (var i = 0; i < 30; i++) {
res = a + b;
a = b;
b = res;
}
}
console.log("value is:",res);
time = new Date().getTime() - time.getTime();
console.log('js',time+'ms');
}
function addon(){
var time = new Date();
x.fib();
time = new Date().getTime() - time.getTime();
console.log('addon c++',time+'ms');
}
function assb(){
var time = new Date();
x.assb();
time = new Date().getTime() - time.getTime();
console.log('addon c++ / inline asm',time+'ms');
}
jstest();
addon();
assb();
c++
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
long a,b,c;
for(int i=0;i<1000000;i++ ){
a = 0;
b = 1;
for(int t=0;t<30;t++){
c=a+b;
a = b;
b = c;
}
}
std::cout<<"value is: "<<c<<std::endl;
c++ inline asm
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
int b;
__asm__ __volatile__(
"movl $100000, %%edi\n\t"
"jmp .L2\n\t"
".L3:\n\t"
"movq %%rdx, %%rcx\n\t"
"movq %%rsi, %%rdx\n\t"
".L5:\n\t"
"leaq (%%rcx,%%rdx), %%rsi\n\t"
"subl $1, %%eax\n\t"
"jne .L3\n\t"
"subl $1, %%edi\n\t"
"je .L7\n\t"
".L2:\n\t"
"movl $30, %%eax\n\t"
"movl $1, %%edx\n\t"
"movl $1, %%ecx\n\t"
"jmp .L5\n\t"
".L7:\n\t"
"movq %%rdx,%%rax\n\t"
"movl %%eax,%0\n\t"
:"=a" (b)
);
std::cout<<"value is: "<<b<<std::endl;
结果
value is: 1346269 js 115ms value is: 1346269 addon c++ 31ms value is: 1346269 addon c++ / inline asm 3ms
配置
Intel® Xeon® CPU E5-2430 0 @ 2.20GHz -单核 512MB 阿里云
后话
我开始自己写了LOOP体汇编。居然跟JS的性能差不多!后来直接反编译C。得到了上面的性能代码,瀑布汗。 可挑战CPU密集型业务。