4

在我的双核机器上,Node JS 比用 C 编写的等效程序运行得更快。

node 优化得这么好,实际上效率更高,还是我的 C 程序有什么问题使它变慢?

节点js代码:

var Parallel = require("paralleljs"); 

function slow(n){
    var i = 0; 
    while(++i < n * n){}
    return i; 
}

var p = new Parallel([20001, 32311, 42222]);
p.map(slow).then(function(data){
    console.log("Done!"+data.toString()); 
});

C代码:

#include <stdio.h>
#include <pthread.h>

struct thread_s {
    long int n; 
    long int r; 
}; 

void *slow(void *p){
    thread_s *t = (thread_s*)p; 
    long int i = 0; 
    while(++i < t->n * t->n){}
    t->r = i; 
    pthread_exit( 0 ); 
}

thread_s arr[] = {{20001, 0}, {32311, 0}, {42222, 0}};

int main(){
    pthread_t t[3]; 
    for(int c = 0; c < 3; c++){
        pthread_create(&t[c], NULL, slow, &arr[c]); 
    }
    for(int c = 0; c < 3; c++){
        pthread_join(t[c], NULL); 
    }
    printf("Done! %ld %ld %ld\n", arr[0].r, arr[1].r, arr[2].r); 
    return 0; 
}
4

3 回答 3

2

您正在对一个玩具程序进行基准测试,这不是比较编译器的好方法。此外,您正在执行的循环没有副作用。它所做的只是设置in * n. 应该优化循环。您是否运行未优化?

尝试计算一些真实的东西,它近似于您稍后将在生产中应用的工作量。例如,如果您的代码会大量使用数字,您可以对一个简单的矩阵乘法进行基准测试。

于 2013-09-28T10:39:03.743 回答
0

Question currently lacks details on benchmark, so it is impossible to say anything definitive about it. However, general comparison between V8 running javascript, and a bknary program compiled from C source is possible.

V8 is pretty darn good at JIT compilation, so while there is the overhead of JIT compilation, this compensates for dynamic nature of JavaScript, so for simple integer operations in a loop there's no reason for JIT code to be slower. JIT

Another consideration is startup time. If you load node.js first and load javascript from interactive prompt, startup time of script is minimal even with JIT, especially compared to dynamically linked binary which needs to resolve symbols etc. If you have small statically linked binary, it will start very fast, and will have done a lot of processing by the time a new node.js is even started and starts to look for some Javascript to execute. You need to be careful how you handle this in benchmarks, or results will be meaningless.

于 2013-09-28T15:17:18.110 回答
0

所有基本操作(+-、Math.xx 等)都映射到 V8 引擎,它只是作为 C 程序执行。因此,在这种情况下,C 与 Node.js 的结果应该完全相同。

我也尝试过 C#.NET vs Node Fibonacci of 45。我第一次运行 C# 时慢了 5 倍,这真的很奇怪。一会儿我明白这是由于我运行 C# 应用程序的调试模式。

即将发布使其非常接近(20sec 节点,22sec C#),可能这只是测量不一致。

无论如何,这只是百分比的问题。

于 2013-09-28T12:18:26.260 回答