diff --git a/host/host.go b/host/host.go index 85d4053..5a800a7 100644 --- a/host/host.go +++ b/host/host.go @@ -6,7 +6,10 @@ import ( "github.com/shirou/gopsutil/internal/common" ) -var invoke common.Invoker +var ( + invoke common.Invoker + cachedBootTime = uint64(0) +) func init() { invoke = common.Invoke{} diff --git a/host/host_darwin.go b/host/host_darwin.go index f802e40..08e9809 100644 --- a/host/host_darwin.go +++ b/host/host_darwin.go @@ -66,6 +66,9 @@ func Info() (*InfoStat, error) { } func BootTime() (uint64, error) { + if cachedBootTime != 0 { + return cachedBootTime, nil + } values, err := common.DoSysctrl("kern.boottime") if err != nil { return 0, err @@ -76,8 +79,9 @@ func BootTime() (uint64, error) { if err != nil { return 0, err } + cachedBootTime = uint64(boottime) - return uint64(boottime), nil + return cachedBootTime, nil } func uptime(boot uint64) uint64 { diff --git a/host/host_freebsd.go b/host/host_freebsd.go index b764472..481d3df 100644 --- a/host/host_freebsd.go +++ b/host/host_freebsd.go @@ -69,6 +69,9 @@ func Info() (*InfoStat, error) { } func BootTime() (uint64, error) { + if cachedBootTime != 0 { + return cachedBootTime, nil + } values, err := common.DoSysctrl("kern.boottime") if err != nil { return 0, err @@ -80,6 +83,7 @@ func BootTime() (uint64, error) { if err != nil { return 0, err } + cachedBootTime = boottime return boottime, nil } diff --git a/host/host_linux.go b/host/host_linux.go index 1bae4a0..69cc138 100644 --- a/host/host_linux.go +++ b/host/host_linux.go @@ -86,6 +86,9 @@ func Info() (*InfoStat, error) { // BootTime returns the system boot time expressed in seconds since the epoch. func BootTime() (uint64, error) { + if cachedBootTime != 0 { + return cachedBootTime, nil + } filename := common.HostProc("stat") lines, err := common.ReadLines(filename) if err != nil { @@ -101,7 +104,8 @@ func BootTime() (uint64, error) { if err != nil { return 0, err } - return uint64(b), nil + cachedBootTime = uint64(b) + return cachedBootTime, nil } } diff --git a/host/host_test.go b/host/host_test.go index b5376f8..8456d22 100644 --- a/host/host_test.go +++ b/host/host_test.go @@ -40,6 +40,11 @@ func TestBoot_time(t *testing.T) { if v < 946652400 { t.Errorf("Invalid Boottime, older than 2000-01-01") } + + v2, err := BootTime() + if v != v2 { + t.Errorf("cached boot time is different") + } } func TestUsers(t *testing.T) { diff --git a/host/host_windows.go b/host/host_windows.go index abf793e..f983a4f 100644 --- a/host/host_windows.go +++ b/host/host_windows.go @@ -91,11 +91,15 @@ func bootTime(up uint64) uint64 { } func BootTime() (uint64, error) { + if cachedBootTime != 0 { + return cachedBootTime, nil + } up, err := Uptime() if err != nil { return 0, err } - return bootTime(up), nil + cachedBootTime = bootTime(up) + return cachedBootTime, nil } func PlatformInformation() (platform string, family string, version string, err error) {