processinfo

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 27, 2023 License: MIT Imports: 3 Imported by: 1

README

processinfo GoDoc Github release Test status

processinfo is a package that lets you get process stats, such as overall CPU utilization and memory usage.

Features

  • Ability to get process information every N seconds.
  • Easy-to-use interface.
  • Supports Linux and Windows.

Installation

go get github.com/olexnzarov/processinfo

Usage

func GetMemoryUsage(pid int) (uint64, error) {
  return processinfo.Get(pid).Memory
}

// This is a preferred way of getting accurate overall CPU usage of a process.
// This function will return an average for the given time duration.
// It will also block the execution for 'sampleTime' duration.
func GetAverageProcessorUsage(pid int, sampleTime time.Duration) float64 {
  ctx, cancel := context.WithCancel(context.Background())
  defer cancel()
  infoChannel := processinfo.NewSampler(ctx, pid, sampleTime)
  <-infoChannel
  info := <-infoChannel
  return info.CPU
}

// Print process information every 5 seconds until the context ends.
func WatchProcess(ctx context.Context, pid int) {
  infoChannel := processinfo.NewSampler(ctx, pid, time.Second * 5)
  for info := range infoChannel {
    fmt.Printf("Process %d:\n  CPU: %.2f%%\n  Memory: %dbytes\n", pid, info.CPU, info.Memory)
  }
}

Examples

This package was created for use in gofu, a modern process manager. Check it out for examples on how to use this package.

License

This code is available under the MIT license, allowing for free use, modification, and distribution.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSampler

func NewSampler(ctx context.Context, pid int, rate time.Duration) <-chan *ProcessInfo

NewSampler returns a channel to which process information will be sent every 'rate' moment. It will contain an average CPU utilization during that time. The channel will be closed when the context is done. If any error occurs during the sampling, the information sent will be zeroed.

Types

type ProcessInfo

type ProcessInfo struct {
	CPU    float64 // Percentage of overall CPU utilization by the process.
	Memory uint64  // Memory used by the process in bytes.
}

func Get

func Get(pid int) (*ProcessInfo, error)

Get returns resources used by the process in the current instant.

It will contain very inaccurate CPU utilization value as it has no time reference. Use 'processinfo.NewSampler' to get an accurate value on ongoing basis.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL