I am running few experiments to see changes in system behavior under different memory and cpu loads. I was wondering is there a bash script which constantly uses high memory but low CPU?
-
1Memory load meaning what, exactly? Memory that's allocated but not actively being accessed is going to get swapped out; if you want memory actually being *accessed*... well, that's doable, but bash wouldn't be my first choice; you'll have *much* more control with a lower-level language. – Charles Duffy Dec 09 '15 at 00:09
-
1This should be done in C. With large mallocs. – 4ae1e1 Dec 09 '15 at 00:15
-
Have you seen this? http://stackoverflow.com/questions/4964799/write-a-bash-shell-script-that-consumes-a-constant-amount-of-ram-for-a-user-defi – Marek Galinski Dec 09 '15 at 00:25
-
@CharlesDuffy yes I just want memory that's allocated and can be swapped out. Actively accessing it is not necessary. – brokendreams Dec 09 '15 at 02:17
-
What do you expect that to accomplish? Memory that's allocated and never accessed at all may be purely virtual and never even get physical pages mapped at all, meaning that it would have zero performance impact whatsoever (on a 64-bit system or similar). – Charles Duffy Dec 09 '15 at 02:20
2 Answers
For the purpose of simulating CPU/memory/IO load, most *NIX systems (Linux included) provide handy tool called stress
.
The tool varies from OS to OS. On Linux, to take up 512MB of RAM with low CPU load:
stress --vm 1 --vm-bytes 512M --vm-hang 100
(The invocation means: start one memory thread (--vm 1
), allocate/free 512MB of memory in every thread, sleep before freeing memory 100 seconds.)

- 16,630
- 5
- 41
- 63
-
An excellent answer: This is much, *much* more practically useful than mere static allocation, despite the OP saying they're only interested in the latter. – Charles Duffy Dec 09 '15 at 15:17
-
I won't judge: I have seen way too many production *NIX systems with only bare-bone OS installed. In the situation, shell/sed/awk is pretty much the only tools available. – Dummy00001 Dec 09 '15 at 15:40
This is silly, and can't be reasonably expected to provide data which will be useful in any real-world scenario. However, to generate at least the amount of memory consumption associated with a given power-of-two bytes:
build_string() {
local pow=$1
local dest=$2
s=' '
for (( i=0; i<pow; i++ )); do
s+="$s"
done
printf -v "$dest" %s "$s"
}
build_string 10 kilobyte # build a string of length 1024
echo "Kilobyte string consumes ${#kilobyte} bytes"
build_string 20 megabyte # build a string of length 1048576
echo "Megabyte string consumes ${#megabyte} bytes"
Note that transiently, during construction, at least 2x the requested space will be required (for the local); a version that didn't have this behavior would either be using namevars (depending on bash 4.3) or eval (depending on the author's willingness to do evil).

- 280,126
- 43
- 390
- 441