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
This commit is contained in:
Ata 2020-09-11 10:41:01 +03:00 committed by GitHub
parent 8a625ec054
commit 5fd5d64304
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 0 deletions

View File

@ -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
}