get system boot time in seconds in go

To get the system boot time in seconds using Go, you can use the boottime function from the syscall package. This function returns a Timeval struct which contains the boot time in seconds and microseconds.

main.go
package main

import (
	"fmt"
	"syscall"
	"time"
)

func main() {
	var bootTime syscall.Timeval
	if err := syscall.SysctlByName("kern.boottime", &bootTime); err != nil {
		panic(err)
	}

	bootSeconds := bootTime.Sec + bootTime.Usec/1e6
	nowSeconds := time.Now().Unix()
	fmt.Printf("System boot time: %d seconds ago\n", nowSeconds-bootSeconds)
}
345 chars
19 lines

In this code, we first declare a Timeval variable bootTime. We then use the syscall.SysctlByName function to get the boot time from the kern.boottime system control variable. If there is an error, we panic.

We then calculate the boot time in seconds by adding the Sec field of the Timeval struct, which contains the number of seconds since the epoch, and the Usec field, which contains the number of microseconds. We divide the Usec field by 1e6 to convert it to seconds.

Finally, we get the current time in seconds using the time.Now().Unix() function and print the difference between current time and boot time in seconds.

related categories

gistlibby LogSnag