From 55dedcc88e5c90c25d1853a0d330ff34261a5fbe Mon Sep 17 00:00:00 2001 From: Daoming Qiu Date: Sat, 27 Aug 2022 17:53:33 +0800 Subject: [PATCH] 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%. --- src/node_main_instance.cc | 16 ++++++++++++++++ src/node_options.cc | 7 +++++++ src/node_options.h | 1 + 3 files changed, 24 insertions(+) diff --git a/src/node_main_instance.cc b/src/node_main_instance.cc index 12d51743dddaca..99a4f728145ad1 100644 --- a/src/node_main_instance.cc +++ b/src/node_main_instance.cc @@ -19,6 +19,10 @@ #if HAVE_INSPECTOR #include "inspector/worker_inspector.h" // ParentInspectorHandle #endif +#if defined(__linux__) +#include +#include +#endif namespace node { @@ -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); diff --git a/src/node_options.cc b/src/node_options.cc index 0869cbb974be86..a02b2c03383cc9 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -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", diff --git a/src/node_options.h b/src/node_options.h index ca43192d85a4b4..11264f94e75842 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -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 cmdline; inline PerIsolateOptions* get_per_isolate_options();