yorkie/me

How to use libomp at Node.js addon(node-gyp)

yorkie opened this issue · 0 comments

OpenMP is an awesome parallelism computing tool for C/C++, recently I'm working on a Node.js project which requires OpenMP to boost the application performance on Macbook.

Unfortunately, after having googled a few hours, there are no practices about node-gyp with libomp(OpenMP), thus I decided to achieve this by myself :)

Install

Firstly, we need to install the libomp on Macbook, I use homebrew to do that via the following command:

$ brew install libomp

Oops, you might occur an error that told you there is no binary for your OSX, just run the following to fix that:

$ brew install --build-from-source libomp

Test

Now, we need to test if OpenMP is working on your machine, here is an example source code:

#include <iostream>

int main()
{
  #pragma omp parallel
  {
    std::cout << "Hello World" << std::endl;
  }
  return 0;
}

OpenMP is not working with default clang, but gcc-{n} is working, such as gcc-8 and gcc-10, at my Macbook, I used the gcc-10 to compile this example.

$ gcc-10 -fopenmp main.cc

And executed the ./out which is compiled by the above, it outputs:

Hello World
Hello World
Hello World
...
Hello World

Congratulations! The OpenMP is working for you!

Final: compile with node-gyp

Now, we could configure your binding.gyp to make libomp work with node-gyp:

"conditions": [
  ['OS=="mac"', {
    "xcode_settings": {
      "OTHER_CPLUSPLUSFLAGS": [
        "-fopenmp",
      ],
    },
  }],
]

Add the above config OTHER_CPLUSPLUSFLAGS [ "-fopenmp" ] to enable OpenMP for your target/targets.

If you wanna use OpenMP runtime library, add the following to the linking config:

"libraries": [
  "-L<!@(brew --prefix libomp)/lib -lomp",
]

Finally, we could use OpenMP directives and runtime functions at Node.js addon!