Admins eHow SysAdmin Tips & Tricks

January 11, 2022

Log the memory usage of a process in Linux

Filed under: linux — Tags: , , , — admin @ 10:27 pm

Create log_memory_usage.py with following contents :

#! /usr/bin/python3

import json, psutil, datetime, sys, time

f = open('memory_usage_'+sys.argv[1]+'.log', 'a')

while True:
  txt=json.dumps((datetime.datetime.now().isoformat(),psutil.Process(int(sys.argv[1])).memory_info()._asdict()))+"\n"
  f.write(txt)
  f.flush()
  time.sleep(60)

Make it executable :

chmod +x log_memory_usage.py

Usage :

./log_memory_usage.py PID

By default it logs the memory usage info every 60 seconds in a file named memory_usage_PID.log in the same folder, if you want, you can change time.sleep(60) in the code to suit your needs.

May 12, 2009

Check Memory Usage in Linux

Filed under: CentOS,Debian,General — Tags: , — admin @ 5:39 pm

In order to check memory usage in Linux , there are several commands , but the most useful commands I have found are the following :

Check total memory usage :

# free -m
total       used       free     shared    buffers     cached
Mem:           512        490         21          0         16        160
-/+ buffers/cache:        314        197
Swap:         1023         76        947

what you are looking for is in front of “-/+ buffers/cache:” , in above example Total memory is 512MB , Used memory is 314MB and Free memory is 197MB.
it also shows the usage of Swap which is 76MB from 1023MB Total.

Check detailed processes memory usage :

# ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr
10.0 1 (squid)
2.7 1 python
1.5 1 /usr/sbin/pdns_recursor
1.3 1 sshd:
1.3 1 /usr/sbin/apache2
.........

This command is a little complex , we dont want to go into the details of command. we are only interested in the output.
The First column shows the percent of memory which this process is using , second column shows the number of instances of the process and the third column is the name of process. in the above example , process “squid” is using 10% of my server memory and python is using 2.7% of memory.

Powered by WordPress