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.go345 chars19 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.
gistlibby LogSnag