github.com/kayoticsully/syncthing@v0.8.9-0.20140724133906-c45a2fdc03f8/cmd/syncthing/gui_unix.go (about)

     1  // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
     2  // All rights reserved. Use of this source code is governed by an MIT-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //+build !windows,!solaris
     6  
     7  package main
     8  
     9  import (
    10  	"syscall"
    11  	"time"
    12  )
    13  
    14  func init() {
    15  	go trackCPUUsage()
    16  }
    17  
    18  func trackCPUUsage() {
    19  	var prevUsage int64
    20  	var prevTime = time.Now().UnixNano()
    21  	var rusage syscall.Rusage
    22  	for _ = range time.NewTicker(time.Second).C {
    23  		syscall.Getrusage(syscall.RUSAGE_SELF, &rusage)
    24  		curTime := time.Now().UnixNano()
    25  		timeDiff := curTime - prevTime
    26  		curUsage := rusage.Utime.Nano() + rusage.Stime.Nano()
    27  		usageDiff := curUsage - prevUsage
    28  		cpuUsageLock.Lock()
    29  		copy(cpuUsagePercent[1:], cpuUsagePercent[0:])
    30  		cpuUsagePercent[0] = 100 * float64(usageDiff) / float64(timeDiff)
    31  		cpuUsageLock.Unlock()
    32  		prevTime = curTime
    33  		prevUsage = curUsage
    34  	}
    35  }