Skip to content

Commit

Permalink
Fix uptime calculation under Windows (#126)
Browse files Browse the repository at this point in the history
Uptime calculation under Windows was broken as it was interpreting the
result of GetTickCount64 as a timestamp relative to UNIX epoch, but it's
just an elapsed time in milliseconds.
  • Loading branch information
adriansr authored Jul 15, 2019
1 parent f75810d commit f48d9dc
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 18 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).

### Fixed

- Fixed uptime calculation under Windows. #126

### Changed

### Deprecated
Expand Down
22 changes: 4 additions & 18 deletions sigar_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"

Expand All @@ -24,11 +23,6 @@ var (
// 2003 and XP where PROCESS_QUERY_LIMITED_INFORMATION is unknown. For all newer
// OS versions it is set to PROCESS_QUERY_LIMITED_INFORMATION.
processQueryLimitedInfoAccess = windows.PROCESS_QUERY_LIMITED_INFORMATION

// bootTime is the time when the OS was last booted. This value may be nil
// on operating systems that do not support the WMI query used to obtain it.
bootTime *time.Time
bootTimeLock sync.Mutex
)

func init() {
Expand Down Expand Up @@ -63,19 +57,11 @@ func (self *Uptime) Get() error {
if !version.IsWindowsVistaOrGreater() {
return ErrNotImplemented{runtime.GOOS}
}

bootTimeLock.Lock()
defer bootTimeLock.Unlock()
if bootTime == nil {
uptime, err := windows.GetTickCount64()
if err != nil {
return errors.Wrap(err, "failed to get boot time using win32 api")
}
var boot = time.Unix(int64(uptime), 0)
bootTime = &boot
uptimeMs, err := windows.GetTickCount64()
if err != nil {
return errors.Wrap(err, "failed to get boot time using GetTickCount64 api")
}

self.Length = time.Since(*bootTime).Seconds()
self.Length = float64(time.Duration(uptimeMs)*time.Millisecond) / float64(time.Second)
return nil
}

Expand Down

0 comments on commit f48d9dc

Please sign in to comment.