
Issue #19443 has been updated by byroot (Jean Boussier). ```ruby require 'benchmark/ips' Benchmark.ips do |x| x.report("Process.pid") { Process.pid } end ``` On macOS where `getpid()` is still cached: ``` ruby 3.2.0 (2022-12-25 revision a528908271) [arm64-darwin22] Warming up -------------------------------------- Process.pid 1.879M i/100ms Calculating ------------------------------------- Process.pid 18.682M (± 2.1%) i/s - 93.968M in 5.032405s ``` On the same machine, but using the docker `ruby:3.2` image (glibc based) ``` ruby 3.2.0 (2022-12-25 revision a528908271) [aarch64-linux] Warming up -------------------------------------- Process.pid 356.920k i/100ms Calculating ------------------------------------- Process.pid 3.539M (± 1.3%) i/s - 17.846M in 5.042975s ``` My branch on macOS: ``` ruby 3.3.0dev (2023-02-16T18:42:31Z cache-process-pid 0cd4797132) [arm64-darwin22] Warming up -------------------------------------- Process.pid 1.804M i/100ms Calculating ------------------------------------- Process.pid 18.465M (± 1.3%) i/s - 93.812M in 5.081288s ``` I'll try to build that branch in a docker container to benchmark it on glibc, but given the implementation I expect the same performance. ---------------------------------------- Feature #19443: Cache `Process.pid` https://bugs.ruby-lang.org/issues/19443#change-101908 * Author: byroot (Jean Boussier) * Status: Open * Priority: Normal ---------------------------------------- It's not uncommon for database client and similar network libraries to protect themselves from Process.fork by regularly checking Process.pid Until recently most libc would cache `getpid()` so this was a cheap check to make. However as of glibc version 2.25 the PID cache is removed and calls to `getpid()` always invoke the actual system call which significantly degrades the performance of existing applications. The reason glibc removed the cache is that some libraries were bypassing `fork(2)` by issuing system calls themselves, causing stale cache issues. That isn't a concern for Ruby as bypassing MRI's primitive for forking would render the VM unusable, so we can safely cache the PID. An example of the issue: https://github.com/rails/rails/issues/47418 Patch: https://github.com/ruby/ruby/pull/7326 -- https://bugs.ruby-lang.org/