Linux code to display CPU temp and utilisation

Having problems installing that new stick of memory? Found some great software or having issues with something? Or maybe want to chat about your PlayStation, X-Box, Nintendo, Sega, even your old Spectrum 48k....! Or maybe something you want to sell or acquire (computing related of course!). Let us know here...
Post Reply
chriscambridge
Active UBT Contributor 1+ yr
Posts: 2110
Joined: Mon Aug 08, 2016 1:56 pm
Location: UK

Linux code to display CPU temp and utilisation

Post by chriscambridge » Sun Feb 21, 2021 9:56 am

In case anyone is interested, this is the bash script code to display your CPU's temp and % utilisation.

Animated GIF showing script in action:

Image

Link to full screen Youtube video showing script in action:

https://www.youtube.com/watch?v=b0_jVtb ... sCambridge

Full BASH SCRIPT/CODE:

Code: Select all

#!/bin/bash

# Temperature inputs.
TEMP_INPUT=$(echo /sys/class/hwmon/hwmon1/{temp1_input,temp2_input,temp3_input})

PREV_TOTAL=0
PREV_IDLE=0

while true; do
  # Get the total CPU statistics, discarding the 'cpu ' prefix.
  CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
  IDLE=${CPU[3]} # Just the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Calculate highest CPU Temperature.
  HIGH_TEMP=$(echo "scale=1; $(sort -r $TEMP_INPUT | head -n1) / 1000" | bc)

  # Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

  # Wait before checking again.
  sleep 1
done
INSTRUCTIONS FOR LINUX MINT:

1) Name the code filname.sh

2) Run the following chmod command on the file:

Code: Select all

chmod +x filename.sh
3) Run the file:

Code: Select all

./filename.sh
CHANGE OUTPUT FROM TERMINAL TO TEXT FILE

just change the line:

Code: Select all

# Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%"
to:

Code: Select all

# Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%" >> cpu.txt
Image

UBT - Timbo
UBT Forum Admin
Posts: 8970
Joined: Mon Mar 13, 2006 12:00 am
Location: NW Midlands
Contact:

Re: Linux code to display CPU temp and utilisation

Post by UBT - Timbo » Sun Feb 21, 2021 12:54 pm

Hi Chris

Thanks for this....just a shame I don't currently run any Linux machines as I'd love to try it out (or give it a "bash" ;-) ).

I'm sure other members might be able to benefit from this :-)

regards
Tim

chriscambridge
Active UBT Contributor 1+ yr
Posts: 2110
Joined: Mon Aug 08, 2016 1:56 pm
Location: UK

Re: Linux code to display CPU temp and utilisation

Post by chriscambridge » Tue Feb 23, 2021 8:17 am

I wanted to update this post, with some instructions on how one can get access to the CPU temp and utilisation in code, but on Windows OS rather than Linux.

I don't have any working code yet that has been tested, but I thought I would share something that I just found which hopefully should provide the interface to get this information. Unfortunately on Windows its a lot harder to get access to the CPU information in code which means you have to rely on an app to export/api out the info.

People may have heard of the program: Open Hardware Monitor (OHM). What's interesting about this app is the fact that it offers an interface so its measurements can be accessed in code.

Basically OHM comes both as the normal .exe file, but also as a .dll file, which (c/++ coders will know) is basically a library of functions you can code against.

Also something which I think would be of interest to most coder/crunchers, OHM also offers many other stats including GPU temp and utilisation! The following shows what the OHM program can report. I am not show if all of these measurements can be accessed via the .dll file, as its my understanding that temp per CPU core is not exported.

Image

However, there is also another app/library called CPU Thermometer which also provides a .dll that offers functions that can be coded against, and this does provide the CPU temp per core.

http://openhardwaremonitor.org/downloads/
http://www.cputhermometer.com/
Last edited by chriscambridge on Tue Feb 23, 2021 8:22 am, edited 2 times in total.
Image

chriscambridge
Active UBT Contributor 1+ yr
Posts: 2110
Joined: Mon Aug 08, 2016 1:56 pm
Location: UK

Re: Linux code to display CPU temp and utilisation

Post by chriscambridge » Tue Feb 23, 2021 8:19 am

I haven't' used or tested this code but this is an example of using OHM and CT in Python (3.6.5) code:

Code: Select all

import clr #package pythonnet, not clr

openhardwaremonitor_hwtypes = ['Mainboard','SuperIO','CPU','RAM','GpuNvidia','GpuAti','TBalancer','Heatmaster','HDD']
cputhermometer_hwtypes = ['Mainboard','SuperIO','CPU','GpuNvidia','GpuAti','TBalancer','Heatmaster','HDD']
openhardwaremonitor_sensortypes = ['Voltage','Clock','Temperature','Load','Fan','Flow','Control','Level','Factor','Power','Data','SmallData']
cputhermometer_sensortypes = ['Voltage','Clock','Temperature','Load','Fan','Flow','Control','Level']

def initialize_openhardwaremonitor():
    file = 'OpenHardwareMonitorLib.dll'
    clr.AddReference(file)

    from OpenHardwareMonitor import Hardware

    handle = Hardware.Computer()
    handle.MainboardEnabled = True
    handle.CPUEnabled = True
    handle.RAMEnabled = True
    handle.GPUEnabled = True
    handle.HDDEnabled = True
    handle.Open()
    return handle

def initialize_cputhermometer():
    file = 'CPUThermometerLib.dll'
    clr.AddReference(file)

    from CPUThermometer import Hardware
    handle = Hardware.Computer()
    handle.CPUEnabled = True
    handle.Open()
    return handle

def fetch_stats(handle):
    for i in handle.Hardware:
        i.Update()
        for sensor in i.Sensors:
            parse_sensor(sensor)
        for j in i.SubHardware:
            j.Update()
            for subsensor in j.Sensors:
                parse_sensor(subsensor)

def parse_sensor(sensor):
        if sensor.Value is not None:
            if type(sensor).__module__ == 'CPUThermometer.Hardware':
                sensortypes = cputhermometer_sensortypes
                hardwaretypes = cputhermometer_hwtypes
            elif type(sensor).__module__ == 'OpenHardwareMonitor.Hardware':
                sensortypes = openhardwaremonitor_sensortypes
                hardwaretypes = openhardwaremonitor_hwtypes
            else:
                return

            if sensor.SensorType == sensortypes.index('Temperature'):
                print(u"%s %s Temperature Sensor #%i %s - %s\u00B0C" % (hardwaretypes[sensor.Hardware.HardwareType], sensor.Hardware.Name, sensor.Index, sensor.Name, sensor.Value))

if __name__ == "__main__":
    print("OpenHardwareMonitor:")
    HardwareHandle = initialize_openhardwaremonitor()
    fetch_stats(HardwareHandle)
    print("\nCPUMonitor:")
    CPUHandle = initialize_cputhermometer()
    fetch_stats(CPUHandle)
Output:

Code: Select all

OpenHardwareMonitor:
SuperIO Nuvoton NCT6791D Temperature Sensor #0 CPU Core - 42.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #1 Temperature #1 - 35.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #2 Temperature #2 - 34.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #3 Temperature #3 - 25.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #4 Temperature #4 - 101.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #5 Temperature #5 - 16.0°C
SuperIO Nuvoton NCT6791D Temperature Sensor #6 Temperature #6 - 14.0°C
GpuNvidia NVIDIA GeForce GTX 1070 Temperature Sensor #0 GPU Core - 60.0°C
HDD ST31000528AS Temperature Sensor #0 Temperature - 37.0°C
HDD WDC WD20EARX-00PASB0 Temperature Sensor #0 Temperature - 36.0°C
HDD WDC WDS100T2B0B-00YS70 Temperature Sensor #0 Temperature - 40.0°C
HDD WDC WD80EFZX-68UW8N0 Temperature Sensor #0 Temperature - 31.0°C
HDD WDC WD30EFRX-68EUZN0 Temperature Sensor #0 Temperature - 30.0°C
HDD WDC WD80EFZX-68UW8N0 Temperature Sensor #0 Temperature - 33.0°C
HDD Crucial_CT256MX100SSD1 Temperature Sensor #0 Temperature - 40.0°C

CPUMonitor:
CPU Intel Core i7-8700K Temperature Sensor #0 CPU Core #1 - 39.0°C
CPU Intel Core i7-8700K Temperature Sensor #1 CPU Core #2 - 38.0°C
CPU Intel Core i7-8700K Temperature Sensor #2 CPU Core #3 - 37.0°C
CPU Intel Core i7-8700K Temperature Sensor #3 CPU Core #4 - 41.0°C
CPU Intel Core i7-8700K Temperature Sensor #4 CPU Core #5 - 36.0°C
CPU Intel Core i7-8700K Temperature Sensor #5 CPU Core #6 - 47.0°C
Full article on code above:

https://stackoverflow.com/questions/326 ... -in-python
Image

chriscambridge
Active UBT Contributor 1+ yr
Posts: 2110
Joined: Mon Aug 08, 2016 1:56 pm
Location: UK

Re: Linux code to display CPU temp and utilisation

Post by chriscambridge » Tue Feb 23, 2021 8:20 am

And this example shows you how to get the GPU utilisation in code via C#

https://stackoverflow.com/questions/624 ... aremonitor
Image

Post Reply