Skip to content

Instantly share code, notes, and snippets.

@syncom
Last active December 22, 2017 07:43
Show Gist options
  • Save syncom/b709b7a6e86c362cf5aadd05ad270e9c to your computer and use it in GitHub Desktop.
Save syncom/b709b7a6e86c362cf5aadd05ad270e9c to your computer and use it in GitHub Desktop.
A CPU hogger in bash

The following bash script hogs CPU resources (and thus drains laptop battery quickly):

#!/bin/bash
# CPU hogger, using 8 threads
hog='dd if=/dev/urandom | bzip2 -9 >> /dev/null'
cmd=$(echo -n ${hog}; printf " | ${hog}%.0s" {1..7};  echo -n '& read; killall dd')
eval ${cmd}

Explaination:

  • 'dd if=/dev/urandom | bzip2 -9' reads random data from /dev/urandom, and compresses it using the best (most CPU consuming) bzip2 algorithm option. This is the CPU hog.
  • 'cmd' is a string constructed as a bash command that repeats the CPU hog above 8 times.
  • By adding the &, we send the hoggers to background. We then read from stdin and kill all the hoggers.
  • The last line evaluates the 'cmd' string as a command.

The script took a (strong) hint from and thank the StackOverflow thread: https://stackoverflow.com/questions/2925606/how-to-create-a-cpu-spike-with-a-bash-command.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment