Linux - Cache information bash script

This is a little bash script to get the CPU cache ratios on Ubuntu.

1
2
3
4
5
6
Cache Level: (1, 2 or 3)
Cache Type: (data-, instruction or general cache)
Capacity: of the respective cache
Associativity: (set size)
Block capacity: / capacity of a cache line
Number of sets: ((total capacity / block capacity) / associativity)

Concerning the associativity, see https://en.wikipedia.org/wiki/CPU_cache#Associativity.

1
2
3
4
5
6
7
8
9
10
11
for DIR0 in /sys/devices/system/cpu/cpu0/cache/*
do
LEVEL0=$(sudo cat $DIR0\/level)
TYPE0=$(sudo cat $DIR0\/type)
SIZE0=$(sudo cat $DIR0\/size)
ASSOC0=$(sudo cat $DIR0\/ways_of_associativity)
BLOCK0=$(sudo cat $DIR0\/coherency_line_size)
SETS0=$(sudo cat $DIR0\/number_of_sets)

printf "Cache level: %s\nCache type: %s\nCapacity: %s Bytes\nAssociativity: %s\nSets: %s\nBlock size: %s Bytes\n\n" "$LEVEL0" "$TYPE0" "$SIZE0" "$ASSOC0" "$SETS0" "$BLOCK0"
done

Usage:

  1. Save code to file, e.g. ~/cacheinfo.sh
  2. Make it executable: chmod +x cacheinfo.sh
  3. Execute: sudo sh cacheinfo.sh