Merge pull request #289 from DataDog/conor/cache-boot-time

Cache the boot time after first query.
pull/291/head
shirou 8 years ago committed by GitHub
commit a2257218e1

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