Measuring energy usage of a function
I recently needed a way to measure how much energy a piece of code consumes. This is easy to do in Linux using the perf utility assuming the underlying kernel has been built with appropriate flags. This looks something like this
$ sudo perf stat -a -e power/energy-pkg/ ls -la /usr total 116 drwxr-xr-x 14 root root 4096 Mar 28 02:08 . drwxr-xr-x 19 root root 4096 Apr 16 16:02 .. drwxr-xr-x 2 root root 36864 May 7 15:05 bin drwxr-xr-x 2 root root 4096 Apr 18 2022 games drwxr-xr-x 37 root root 16384 May 7 15:51 include drwxr-xr-x 88 root root 4096 May 7 15:05 lib drwxr-xr-x 2 root root 4096 Mar 28 02:08 lib32 drwxr-xr-x 2 root root 4096 Apr 19 06:14 lib64 drwxr-xr-x 9 root root 4096 Apr 16 18:02 libexec drwxr-xr-x 2 root root 4096 Mar 28 02:08 libx32 drwxr-xr-x 10 root root 4096 Mar 28 02:08 local drwxr-xr-x 2 root root 20480 May 7 15:20 sbin drwxr-xr-x 119 root root 4096 May 7 15:05 share drwxr-xr-x 7 root root 4096 Apr 20 06:56 src Performance counter stats for 'system wide': 0.03 Joules power/energy-pkg/ 0.000777146 seconds time elapsed This tells me that the ls command consumed 0.03 Joules of energy and ran for 0.00078 seconds. I needed to get similar data for a C function that might be surrounded by code that I do not need to measure. Something like this:
A blog