Task: Linux CPU utilization




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    fmt.Println("CPU usage % at 1 second intervals:\n")
    var prevIdleTime, prevTotalTime uint64
    for i := 0; i < 10; i++ {
        file, err := os.Open("/proc/stat")
        if err != nil {
            log.Fatal(err)
        }
        scanner := bufio.NewScanner(file)
        scanner.Scan()
        firstLine := scanner.Text()[5:] 
        file.Close()
        if err := scanner.Err(); err != nil {
            log.Fatal(err)
        }
        split := strings.Fields(firstLine)
        idleTime, _ := strconv.ParseUint(split[3], 10, 64)
        totalTime := uint64(0)
        for _, s := range split {
            u, _ := strconv.ParseUint(s, 10, 64)
            totalTime += u
        }
        if i > 0 {
            deltaIdleTime := idleTime - prevIdleTime
            deltaTotalTime := totalTime - prevTotalTime
            cpuUsage := (1.0 - float64(deltaIdleTime)/float64(deltaTotalTime)) * 100.0
            fmt.Printf("%d : %6.3f\n", i, cpuUsage)
        }
        prevIdleTime = idleTime
        prevTotalTime = totalTime
        time.Sleep(time.Second)
    }
}


Java: import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.NumberFormat;
import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;


public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        
        final var period = Duration.ofSeconds(1);
        new Timer().schedule(new CpuUtilizationTask(), 0, period.toMillis());
    }

    
    static class CpuUtilizationTask extends TimerTask {

        private final String STAT_FILE_HEADER = "cpu  ";
        private final NumberFormat percentFormatter;
        private final RandomAccessFile statPointer;
        long previousIdleTime = 0, previousTotalTime = 0;

        public CpuUtilizationTask() throws FileNotFoundException {
            this.percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMaximumFractionDigits(2);
            var statFile = new File("/proc/stat");
            
            this.statPointer = new RandomAccessFile(statFile, "r");
        }

        @Override
        public void run() {

            try {
                var values = statPointer.readLine()
                        .substring(STAT_FILE_HEADER.length())
                        .split(" ");

                
                var idleTime = Long.parseUnsignedLong(values[3]);
                var totalTime = 0L;
                for (String value : values) {
                    totalTime += Long.parseUnsignedLong(value);
                }

                var idleTimeDelta = idleTime - previousIdleTime;
                var totalTimeDelta = totalTime - previousTotalTime;
                var utilization = 1 - ((double) idleTimeDelta) / totalTimeDelta;

                
                System.out.println(percentFormatter.format(utilization));

                previousIdleTime = idleTime;
                previousTotalTime = totalTime;

                
                statPointer.seek(0);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }
}