Question

it's 2:50 AM here and after a hectic day I found something strange. I do my best to give a picture of my problem.

I wrote these two pieces of code in C++ and JavaScript:

#include<stdio.h>
#include <time.h>

int main() {
    clock_t tStart = clock();

    int result = 0;
    for (int a = 0; a < 1000000000;a++) {
        result += a;
    }

    printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);

  return 1;
}

And:

var start = new Date().getTime();

var result = 0;

for(var a = 0;a < 1000000000;a++) {
    result += a;
}

var end = new Date().getTime();
var time = end - start;
console.log('Time taken: ' + (time/1000) + 's');

Both of them do the same thing (I hope so)

After generating ./a.out.js using the latest version of emscripten, I found something weird: the result of executing both codes

The execution time of the emscripten code is really slower than the manually written JavaScript code. What's the problem?

Was it helpful?

Solution

node.js lacks most of the real asm.js performance tweaks that make emscripten fast. Instead of trying it with node, try it in firefox or chrome.

The issue is that node.js tends to lag behind chrome's V8 version, so features (or optimizations) that go into Chrome may take quite awhile to make it into V8. I don't actually know how long, but the asm.js optimizations are new enough that when I last tried it in early April, 2014 it was significantly slower on the command line with node.js than in the browser with Chrome, and Firefox was faster still.

OTHER TIPS

I think you may have a bug somewhere in your compile toolchain. Make sure its not accidentally including the system libraries/headers instead of emscripten's choice. Also make sure you're not accidently using your systems clang.

If you do emcc -v test.cpp (assuming test.cpp is your file your compiling) it should tell you exactly what headers, llvm/clang and node its going to rely on. Below you can see the emcc default compile actually runs faster than out-of-the-box clang native c code (this may seem surprising but V8 does runtime optimizations, C++ does not.)

slcmew-nmx2499:Downloads trevor.linton$ gcc test.cpp
slcmew-nmx2499:Downloads trevor.linton$ ./a.out
Time taken: 2.33s
slcmew-nmx2499:Downloads trevor.linton$ emcc test.cpp
slcmew-nmx2499:Downloads trevor.linton$ node a.out.js
Time taken: 1.17s
slcmew-nmx2499:Downloads trevor.linton$ 

Finally make sure you're using the latest and greatest ./emsdk update and then ./emsdk install latest-64bit. This was tested with node 0.10.21 and emscripten 1.16 on MacOS X Mavericks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top