Cache the boot time after first query.

When fetching stats on all processes at once there's a non-trivial amount of
time spent in the `BootTime` call. But since this value should never change
during a live process, we can use a cached version for all subsequent calls.
pull/289/head
Conor Branagan 9 years ago
parent fc800d3fb4
commit 5afd6f21c9

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

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

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

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

@ -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) {

@ -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) {

Loading…
Cancel
Save