Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
src: add option to set cpu affinity of mainthread
Add runtime option '--set-mainthread-cpu-affinity' to pin the
mainthread to the current running cpu before entering event loop.
This feature is implemented on Linux OS currently.

Enabling this option will benefit node.js applications running on
heavy-workload system and can increase performance for several
node.js benchmarks, ex., several cases in benchmark/vm/ improved
by 40%.
  • Loading branch information
Daoming Qiu committed Aug 30, 2022
commit 55dedcc88e5c90c25d1853a0d330ff34261a5fbe
16 changes: 16 additions & 0 deletions src/node_main_instance.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
#if HAVE_INSPECTOR
#include "inspector/worker_inspector.h" // ParentInspectorHandle
#endif
#if defined(__linux__)
#include <sched.h>
#include <unistd.h>
#endif

namespace node {

Expand Down Expand Up @@ -134,6 +138,18 @@ int NodeMainInstance::Run() {

void NodeMainInstance::Run(int* exit_code, Environment* env) {
if (*exit_code == 0) {
if (per_process::cli_options->set_mainthread_cpu_affinity) {
#if defined(__linux__)
cpu_set_t mask;
int c = sched_getcpu();
if (c >= 0) {
CPU_ZERO(&mask);
CPU_SET(c, &mask);
sched_setaffinity(0, sizeof(cpu_set_t), &mask);
}
#endif
}

LoadEnvironment(env, StartExecutionCallback{});

*exit_code = SpinEventLoop(env).FromMaybe(1);
Expand Down
7 changes: 7 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,13 @@ PerProcessOptionsParser::PerProcessOptionsParser(
&PerProcessOptions::trace_sigint,
kAllowedInEnvironment);

AddOption("--set-mainthread-cpu-affinity",
"enable setting mainthread's cpu affinity to the currently "
"running cpu before entering event loop, implemented on "
"Linux OS only",
&PerProcessOptions::set_mainthread_cpu_affinity,
kAllowedInEnvironment);

Insert(iop, &PerProcessOptions::get_per_isolate_options);

AddOption("--node-memory-debug",
Expand Down
1 change: 1 addition & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ class PerProcessOptions : public Options {
// TODO(addaleax): Some of these could probably be per-Environment.
std::string use_largepages = "off";
bool trace_sigint = false;
bool set_mainthread_cpu_affinity = false;
std::vector<std::string> cmdline;

inline PerIsolateOptions* get_per_isolate_options();
Expand Down