From bbc7e8429bda06534ba2685a9abc7bd2eac45374 Mon Sep 17 00:00:00 2001 From: Brian Gianforcaro Date: Thu, 23 Jul 2020 00:27:33 -0700 Subject: [PATCH] LibC: Remove duplicate gs touch during gettid()/getpid() fast path While profiling I noticed that gettid() was hitting gs register twice, once for the initial fetch of s_cache_tid out of TLS for the initialization check, and then again when we return the actual value. Optimize the implementation to cache the value so we avoid the double fetch during the 99% case where it's already set. With this change gettid() goes from being the 3rd most sampled function in test-js, to pretty much disappearing into ~20th place. Additionally add the same optimization to getpid(). --- Libraries/LibC/unistd.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/Libraries/LibC/unistd.cpp b/Libraries/LibC/unistd.cpp index 9ff0605957..feee5faaea 100644 --- a/Libraries/LibC/unistd.cpp +++ b/Libraries/LibC/unistd.cpp @@ -202,9 +202,12 @@ gid_t getgid() pid_t getpid() { - if (!s_cached_pid) - s_cached_pid = syscall(SC_getpid); - return s_cached_pid; + int cached_pid = s_cached_pid; + if (!cached_pid) { + cached_pid = syscall(SC_getpid); + s_cached_pid = cached_pid; + } + return cached_pid; } pid_t getppid() @@ -608,9 +611,12 @@ int truncate(const char* path, off_t length) int gettid() { - if (!s_cached_tid) - s_cached_tid = syscall(SC_gettid); - return s_cached_tid; + int cached_tid = s_cached_tid; + if (!cached_tid) { + cached_tid = syscall(SC_gettid); + s_cached_tid = cached_tid; + } + return cached_tid; } int donate(int tid)