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

Cache the boot time after first query.
This commit is contained in:
shirou 2016-12-21 14:15:45 +09:00 committed by GitHub
commit a2257218e1
6 changed files with 28 additions and 4 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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