From 5fd5d64304da465c94f64019c7198f40d01e20b2 Mon Sep 17 00:00:00 2001 From: Ata Date: Fri, 11 Sep 2020 10:41:01 +0300 Subject: [PATCH 1/2] Cache common/common_linux.Virtualization() By assuming virtualization environment won't change during a the program's runtime, we can cache common/common_linux.Virtualization() with a simple map to reduce amount of system calls. I first mentioned this issue at https://github.com/shirou/gopsutil/pull/890#issuecomment-690211919 --- internal/common/common_linux.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/internal/common/common_linux.go b/internal/common/common_linux.go index 0f66f1c38..bfbe7d74c 100644 --- a/internal/common/common_linux.go +++ b/internal/common/common_linux.go @@ -110,7 +110,14 @@ func Virtualization() (string, string, error) { return VirtualizationWithContext(context.Background()) } +var virtualizationCache map[string]string = nil + func VirtualizationWithContext(ctx context.Context) (string, string, error) { + // if cached already, return from cache + if virtualizationCache != nil { + return virtualizationCache["system"], virtualizationCache["role"], nil + } + var system string var role string @@ -231,6 +238,13 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) { role = "host" } } + + // before returning for the first time, cache the system and role + virtualizationCache = map[string]string{ + "system": system, + "role": role, + } + return system, role, nil } From ba243b1d14fe9f22ddfd61f57691ad89da817ae9 Mon Sep 17 00:00:00 2001 From: Ata Date: Tue, 29 Sep 2020 10:12:48 +0300 Subject: [PATCH 2/2] removed explicit set to nil --- internal/common/common_linux.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/common/common_linux.go b/internal/common/common_linux.go index bfbe7d74c..62fac5e5c 100644 --- a/internal/common/common_linux.go +++ b/internal/common/common_linux.go @@ -110,7 +110,7 @@ func Virtualization() (string, string, error) { return VirtualizationWithContext(context.Background()) } -var virtualizationCache map[string]string = nil +var virtualizationCache map[string]string func VirtualizationWithContext(ctx context.Context) (string, string, error) { // if cached already, return from cache