简体   繁体   English

Node.js与C ++的性能实现简单数学

[英]Nodejs vs C++ performance for simple mathematic

I made the same program to test performance on Nodejs and C++ on Mac OS X. 我制作了相同的程序来测试Mac OS X上的Nodejs和C ++的性能。

First in C++: 首先在C ++中:

#include <iostream>
#include <time.h>

using namespace std;

int main() {
    clock_t t1, t2;

    cout << "Initializing\n";

    t1 = clock();

    double m = 0;
    for (double i = 0; i != 10000000000; ++i) {
        m = i * -1 + i;
    }

    t2 = clock();
    float diff = (((float) t2 - (float) t1) / 1000000.0F) * 1000;

    cout << "Finalizing with " << diff << "ms\n";
}

Second in Nodejs: 在Nodejs中排名第二:

console.log("Initializing");

t1 = Date.now();

var m = 0;

for (var i = 0; i != 10000000000; i++) {
    m = i * -1 + i;
}

t2 = Date.now();
var diff = t2 - t1;
console.log("Finalizing with %dms", diff);

The result was 50000ms for C++ and 22000 for Nodejs. 对于C ++,结果为50000ms,对于Nodejs,结果为22000ms。

Why Nodejs is faster for that kind of operation? 为什么Node.js在这种操作上更快?

Thanks. 谢谢。

UPDATE: 更新:

Switching double and using long int, it gave me 22000ms, like Nodejs. 切换双倍并使用long int,它给了我22000毫秒,就像Nodejs。

The problem is that the code for 2 languages is not equivalent. 问题是两种语言的代码不相同。 In C++ you used double and in javascript variable was optimized to be integers (although their type is Number which in general case is floating-point type). 在C ++中,您使用了double并且在javascript中将变量优化为整数(尽管它们的类型为Number ,通常情况下为浮点类型)。 And, of course, floating point operations are always longer than operations on integers. 而且,当然,浮点运算总是比整数运算长。

Try to replace double with int or better with long in the C++ version. 尝试用int代替double或在C ++版本中用long更好。 This will ensure you have integers in both versions. 这样可以确保两个版本中都有整数。

If you do that please consider posting results for us to see the difference. 如果您这样做,请考虑发布结果以供我们查看差异。 T Ť

It is quite difficult to measure performance straight off using this type of code. 使用这种类型的代码来衡量性能非常困难。 Both the C++ compiler and the V8 JITter uses different types of optimization of the generated native code. C ++编译器和V8 JITter都对生成的本机代码使用不同类型的优化。

A few things to look out for: 需要注意的几件事:

  • The code i != 10000000000 is dangerous. 代码i != 10000000000是危险的。 Always compare doubles using inequalities ( <> ) rather than equalities ( == , != ). 始终使用不等号( <> )而不是等号( ==!= )比较双精度数。
  • There is no need to use floating point at all, use the long long type instead. 根本不需要使用浮点,而是使用long long类型。 The thing is, NodeJS may actually do this optimization automatically, since it is dynamically typed. 事实是,NodeJS实际上可以自动执行此优化,因为它是动态键入的。
  • You don't actually use m anywhere. 您实际上并没有在任何地方使用m If you compile with g++ -O3 , the compiler may actually optimize away the whole loop (try it!). 如果使用g++ -O3进行编译,则编译器实际上可以优化整个循环(尝试一下!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM