Thursday, October 15, 2009

Linux Memory use

#!/usr/bin/python
import os, sys, time
a="\x00"*(32*1024*1024) #alloc 32MiB
pid=os.fork()
if(not pid):
time.sleep(1)
sys.exit()
sizel=map(float,open("/proc/"+str(pid)+"/statm").readlines()[0].split()[1:3])
print "only %.1f%% reported as shared" % ((sizel[1]/sizel[0])*100)
os.wait()


--

import sys, os, string

if os.geteuid() != 0:
sys.stderr.write("Sorry, root permission required.\n");
sys.exit(1)

PAGESIZE=os.sysconf("SC_PAGE_SIZE")/1024 #KiB
our_pid=os.getpid()

#(major,minor,release)
def kernel_ver():
kv=open("/proc/sys/kernel/osrelease").readline().split(".")[:3]
for char in "-_":
kv[2]=kv[2].split(char)[0]
return (int(kv[0]), int(kv[1]), int(kv[2]))

kv=kernel_ver()

have_pss=0

#return Private,Shared
#Note shared is always a subset of rss (trs is not always)
def getMemStats(pid):
global have_pss
Private_lines=[]
Shared_lines=[]
Pss_lines=[]
Rss=int(open("/proc/"+str(pid)+"/statm").readline().split()[1])*PAGESIZE
if os.path.exists("/proc/"+str(pid)+"/smaps"): #stat
for line in open("/proc/"+str(pid)+"/smaps").readlines(): #open
if line.startswith("Shared"):
Shared_lines.append(line)
elif line.startswith("Private"):
Private_lines.append(line)
elif line.startswith("Pss"):
have_pss=1
Pss_lines.append(line)
Shared=sum([int(line.split()[1]) for line in Shared_lines])
Private=sum([int(line.split()[1]) for line in Private_lines])
#Note Shared + Private = Rss above
#The Rss in smaps includes video card mem etc.
if have_pss:
pss_adjust=0.5 #add 0.5KiB as this average error due to trunctation
Pss=sum([float(line.split()[1])+pss_adjust for line in Pss_lines])
Shared = Pss - Private
elif (2,6,1) <= kv <= (2,6,9):
Shared=0 #lots of overestimation, but what can we do?
Private = Rss
else:
Shared=int(open("/proc/"+str(pid)+"/statm").readline().split()[2])
Shared*=PAGESIZE
Private = Rss - Shared
return (Private, Shared)

def getCmdName(pid):
cmd = file("/proc/%d/status" % pid).readline()[6:-1]
exe = os.path.basename(os.path.realpath("/proc/%d/exe" % pid))
if exe.startswith(cmd):
cmd=exe #show non truncated version
#Note because we show the non truncated name
#one can have separated programs as follows:
#584.0 KiB + 1.0 MiB = 1.6 MiB mozilla-thunder (exe -> bash)
# 56.0 MiB + 22.2 MiB = 78.2 MiB mozilla-thunderbird-bin
return cmd

cmds={}
shareds={}
count={}
for pid in os.listdir("/proc/"):
try:
pid = int(pid) #note Thread IDs not listed in /proc/ which is good
if pid == our_pid: continue
except:
continue
try:
cmd = getCmdName(pid)
except:
#permission denied or
#kernel threads don't have exe links or
#process gone
continue
try:
private, shared = getMemStats(pid)
except:
continue #process gone
if shareds.get(cmd):
if have_pss: #add shared portion of PSS together
shareds[cmd]+=shared
elif shareds[cmd] < shared: #just take largest shared val
shareds[cmd]=shared
else:
shareds[cmd]=shared
cmds[cmd]=cmds.setdefault(cmd,0)+private
if count.has_key(cmd):
count[cmd] += 1
else:
count[cmd] = 1

#Add shared mem for each program
total=0
for cmd in cmds.keys():
cmds[cmd]=cmds[cmd]+shareds[cmd]
total+=cmds[cmd] #valid if PSS available

sort_list = cmds.items()
sort_list.sort(lambda x,y:cmp(x[1],y[1]))
sort_list=filter(lambda x:x[1],sort_list) #get rid of zero sized processes

#The following matches "du -h" output
#see also human.py
def human(num, power="Ki"):
powers=["Ki","Mi","Gi","Ti"]
while num >= 1000: #4 digits
num /= 1024.0
power=powers[powers.index(power)+1]
return "%.1f %s" % (num,power)

def cmd_with_count(cmd, count):
if count>1:
return "%s (%u)" % (cmd, count)
else:
return cmd

print " Private + Shared = RAM used\tProgram \n"
for cmd in sort_list:
print "%8sB + %8sB = %8sB\t%s" % (human(cmd[1]-shareds[cmd[0]]),
human(shareds[cmd[0]]), human(cmd[1]),
cmd_with_count(cmd[0], count[cmd[0]]))
if have_pss:
print "-" * 33
print " " * 24 + "%8sB" % human(total)
print "=" * 33
print "\n Private + Shared = RAM used\tProgram \n"

#Warn of possible inaccuracies
#2 = accurate & can total
#1 = accurate only considering each process in isolation
#0 = some shared mem not reported
#-1= all shared mem not reported
def shared_val_accuracy():
"""http://wiki.apache.org/spamassassin/TopSharedMemoryBug"""
if kv[:2] == (2,4):
if open("/proc/meminfo").read().find("Inact_") == -1:
return 1
return 0
elif kv[:2] == (2,6):
if os.path.exists("/proc/"+str(os.getpid())+"/smaps"):
if open("/proc/"+str(os.getpid())+"/smaps").read().find("Pss:")!=-1:
return 2
else:
return 1
if (2,6,1) <= kv <= (2,6,9):
return -1
return 0
else:
return 1

vm_accuracy = shared_val_accuracy()
if vm_accuracy == -1:
sys.stderr.write(
"Warning: Shared memory is not reported by this system.\n"
)
sys.stderr.write(
"Values reported will be too large, and totals are not reported\n"
)
elif vm_accuracy == 0:
sys.stderr.write(
"Warning: Shared memory is not reported accurately by this system.\n"
)
sys.stderr.write(
"Values reported could be too large, and totals are not reported\n"
)
elif vm_accuracy == 1:
sys.stderr.write(
"Warning: Shared memory is slightly over-estimated by this system\n"
"for each program, so totals are not reported.\n"
)

Performance and Tuning

Kernel

To successfully run enterprise applications, such as a database server, on your Linux distribution, you may be required to update some of the default kernel parameter settings. For example, the 2.4.x series kernel message queue parameter msgmni has a default value (for example, shared memory, or shmmax is only 33,554,432 bytes on Red Hat Linux by default) that allows only a limited number of simultaneous connections to a database. Here are some recommended values (by the IBM DB2 Support Web site) for database servers to run optimally:

- kernel.shmmax=268435456 for 32-bit
- kernel.shmmax=1073741824 for 64-bit
- kernel.msgmni=1024
- fs.file-max=8192
- kernel.sem="250 32000 32 1024"

Shared Memory

To view current settings, run command:
# more /proc/sys/kernel/shmmax

To set it to a new value for this running session, which takes effect immediately, run command:
# echo 268435456 > /proc/sys/kernel/shmmax

To set it to a new value permanently (so it survives reboots), modify the sysctl.conf file:
...
kernel.shmmax = 268435456
...

Semaphores

To view current settings, run command:
# more /proc/sys/kernel/sem
250 32000 32 1024

To set it to a new value for this running session, which takes effect immediately, run command:
# echo 500 512000 64 2048 > /proc/sys/kernel/sem
Parameters meaning:
SEMMSL - semaphores per ID
SEMMNS - (SEMMNI*SEMMSL) max semaphores in system
SEMOPM - max operations per semop call
SEMMNI - max semaphore identifiers

ulimits

To view current settings, run command:
# ulimit -a

To set it to a new value for this running session, which takes effect immediately, run command:
# ulimit -n 8800
# ulimit -n -1 // for unlimited; recommended if server isn't shared

Alternatively, if you want the changes to survive reboot, do the following:

- Exit all shell sessions for the user you want to change limits on.
- As root, edit the file /etc/security/limits.conf and add these two lines toward the end:
user1 soft nofile 16000
user1 hard nofile 20000
** the two lines above changes the max number of file handles - nofile - to new settings.
- Save the file.
- Login as the user1 again. The new changes will be in effect.


Message queues

To view current settings, run command:
# more /proc/sys/kernel/msgmni
# more /proc/sys/kernel/msgmax

To set it to a new value for this running session, which takes effect immediately, run command:
# echo 2048 > /proc/sys/kernel/msgmni
# echo 64000 > /proc/sys/kernel/msgmax

Network

Gigabit-based network interfaces have many performance-related parameters inside of their device driver such as CPU affinity. Also, the TCP protocol can be tuned to increase network throughput for connection-hungry applications.

Tune TCP

To view current TCP settings, run command:
# sysctl net.ipv4.tcp_keepalive_time
net.ipv4.tcp_keepalive_time = 7200 // 2 hours
where net.ipv4.tcp_keepalive_time is a TCP tuning parameter.

To set a TCP parameter to a value, run command:
# sysctl -w net.ipv4.tcp_keepalive_time=1800

A list of recommended TCP parameters, values, and their meanings:

Tuning Parameter Tuning Value Description of impact
------------------------------------------------------------------------------
net.ipv4.tcp_tw_reuse
net.ipv4.tcp_tw_recycle 1 Reuse sockets in the time-wait state
---
net.core.wmem_max 8388608 Increase the maximum write buffer queue size
---
net.core.rmem_max 8388608 Increase the maximum read buffer queue size
---
net.ipv4.tcp_rmem 4096 87380 8388608 Set the minimum, initial, and maximum sizes for the
read buffer. Note that this maximum should be less
than or equal to the value set in net.core.rmem_max.
---
net.ipv4.tcp_wmem 4096 87380 8388608 Set the minimum, initial, and maximum sizes for the
write buffer. Note that this maximum should be less
than or equal to the value set in net.core.wmem_max.
---
timeout_timewait echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout Determines the time that must elapse before
TCP/IP can release a closed connection and reuse its resources.
This interval between closure and release is known as the TIME_WAIT
state or twice the maximum segment lifetime (2MSL) state.
During this time, reopening the connection to the client and
server cost less than establishing a new connection. By reducing the
value of this entry, TCP/IP can release closed connections faster, providing
more resources for new connections. Adjust this parameter if the running application
requires rapid release, the creation of new connections, and a low throughput
due to many connections sitting in the TIME_WAIT state.

Disk I/O

Choose the Right File System

Use 'ext3' file system in Linux.
- It is enhanced version of ext2
- With journaling capability - high level of data integrity (in event of unclean shutdown)
- It does not need to check disks on unclean shutdown and reboot (time consuming)
- Faster write - ext3 journaling optimizes hard drive head motion

# mke2fs -j -b 2048 -i 4096 /dev/sda
mke2fs 1.32 (09-Nov-2002)
/dev/sda is entire device, not just one partition!
Proceed anyway? (y,n) y
Filesystem label=
OS type: Linux
Block size=2048 (log=1)
Fragment size=2048 (log=1)
13107200 inodes, 26214400 blocks
1310720 blocks (5.00%) reserved for the super user
First data block=0
1600 block groups
16384 blocks per group, 16384 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
16384, 49152, 81920, 114688, 147456, 409600, 442368, 802816, 1327104,
2048000, 3981312, 5619712, 10240000, 11943936

Writing inode tables: done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 28 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

Use 'noatime' File System Mount Option

Use 'noatime' option in the file system boot-up configuration file 'fstab'. Edit the fstab file under /etc. This option works the best if external storage is used, for example, SAN:

# more /etc/fstab
LABEL=/ / ext3 defaults 1 1
none /dev/pts devpts gid=5,mode=620 0 0
none /proc proc defaults 0 0
none /dev/shm tmpfs defaults 0 0
/dev/sdc2 swap swap defaults 0 0
/dev/cdrom /mnt/cdrom udf,iso9660 noauto,owner,kudzu,ro 0 0
/dev/fd0 /mnt/floppy auto noauto,owner,kudzu 0 0
/dev/sda /database ext3 defaults,noatime 1 2
/dev/sdb /logs ext3 defaults,noatime 1 2
/dev/sdc /multimediafiles ext3 defaults,noatime 1 2

Tune the Elevator Algorithm in Linux Kernel for Disk I/O

After choosing the file system, there are several kernel and mounting options that can affect it. One such kernel setting is the elevator algorithm. Tuning the elevator algorithm helps the system balance the need for low latency with the need to collect enough data to efficiently organize batches of read and write requests to the disk. The elevator algorithm can be adjusted with the following command:

# elvtune -r 1024 -w 2048 /dev/sda
/dev/sda elevator ID 2
read_latency: 1024
write_latency: 2048
max_bomb_segments: 6

The parameters are: read latency (-r), write latency (-w) and the device affected.
Red Hat recommends using a read latency half the size of the write latency (as shown).
As usual, to make this setting permanent, add the 'elvtune' command to the
/etc/rc.d/rc.local script.

Others

Disable Unnecessary Daemons (They Take up Memory and CPU)

There are daemons (background services) running on every server that are probably not needed. Disabling these daemons frees memory, decreases startup time, and decreases the number of processes that the CPU has to handle. A side benefit to this is increased security of the server because fewer daemons mean fewer exploitable processes.


Some example Linux daemons running by default (and should be disabled). Use command:

#/sbin/chkconfig --levels 2345 sendmail off
#/sbin/chkconfig sendmail off

Daemon


Description

apmd


Advanced power management daemon

autofs


Automatically mounts file systems on demand (i.e.: mounts a CD-ROM automatically)

cups


Common UNIX� Printing System

hpoj


HP OfficeJet support

isdn


ISDN modem support

netfs


Used in support of exporting NFS shares

nfslock


Used for file locking with NFS

pcmcia


PCMCIA support on a server

rhnsd


Red Hat Network update service for checking for updates and security errata

sendmail


Mail Transport Agent

xfs


Font server for X Windows

Shutdown GUI

Normally, there is no need for a GUI on a Linux server. All administration tasks can be achieved by the command line, redirecting the X display or through a Web browser interface. Modify the 'inittab' file to set boot level as 3:

To set the initial runlevel (3 instead of 5) of a machine at boot,
modify the /etc/inittab file as shown:

http://i35.tinypic.com/2d2jdbr.jpg

How do I Find Out Linux CPU Utilization


Whenever a Linux system CPU is occupied by a process, it is unavailable for processing other requests. Rest of pending requests must wait till CPU is free. This becomes a bottleneck in the system. Following command will help you to identify CPU utilization, so that you can troubleshoot CPU related performance problems.

Finding CPU utilization is one of the important tasks. Linux comes with various utilities to report CPU utilization. With these commands, you will be able to find out:

* CPU utilization
* Display the utilization of each CPU individually (SMP cpu)
* Find out your system's average CPU utilization since the last reboot etc
* Determine which process is eating the CPU(s)
Old good top command to find out Linux cpu load

The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks currently being managed by the Linux kernel.
The top command monitors CPU utilization, process statistics, and memory utilization. The top section contains information related to overall system status - uptime, load average, process counts, CPU status, and utilization statistics for both memory and swap space.
Top command to find out Linux cpu usage

Type the top command:
$ top

Output:

You can see Linux CPU utilization under CPU stats. The task’s share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time. In a true SMP environment (multiple CPUS), top will operate in number of CPUs. Please note that you need to type q key to exit the top command display.

The top command produces a frequently-updated list of processes. By default, the processes are ordered by percentage of CPU usage, with only the "top" CPU consumers shown. The top command shows how much processing power and memory are being used, as well as other information about the running processes.
Find Linux CPU utilization using mpstat and other tools

Please note that you need to install special package called sysstat to take advantage of following commands. This package includes system performance tools for Linux (Red Hat Linux / RHEL includes these tools by default).

# apt-get install sysstat
Use up2date command if you are using RHEL:
# up2date sysstat
Display the utilization of each CPU individually using mpstat

If you are using SMP (Multiple CPU) system, use mpstat command to display the utilization of each CPU individually. It report processors related statistics. For example, type command:
# mpstat Output:

Linux 2.6.15.4 (debian) Thursday 06 April 2006

05:13:05 IST CPU %user %nice %sys %iowait %irq %soft %steal %idle intr/s
05:13:05 IST all 16.52 0.00 2.87 1.09 0.07 0.02 0.00 79.42 830.06

The mpstat command display activities for each available processor, processor 0 being the first one. Global average activities among all processors are also reported. The mpstat command can be used both on SMP and UP machines, but in the latter, only global average activities will be printed.:
# mpstat -P ALL
Output:

Linux 2.6.15.4 (wwwportal1.xxxx.co.in) Thursday 06 April 2006

05:14:58 IST CPU %user %nice %sys %iowait %irq %soft %steal %idle intr/s
05:14:58 IST all 16.46 0.00 2.88 1.08 0.07 0.02 0.00 79.48 835.96
05:14:58 IST 0 16.46 0.00 2.88 1.08 0.07 0.02 0.00 79.48 835.96
05:14:58 IST 1 15.77 2.70 3.17 2.01 0.05 0.03 0.00 81.44 822.54

Another output from my HP Dual Opteron 64 bit server:# mpstat -P ALLOutput:

Linux 2.6.5-7.252-smp (ora9.xxx.in) 04/07/06

07:44:18 CPU %user %nice %system %iowait %irq %soft %idle intr/s
07:44:18 all 3.01 57.31 0.36 0.13 0.01 0.00 39.19 1063.46
07:44:18 0 5.87 69.47 0.44 0.05 0.01 0.01 24.16 262.11
07:44:18 1 1.79 48.59 0.36 0.23 0.00 0.00 49.02 268.92
07:44:18 2 2.19 42.63 0.28 0.16 0.01 0.00 54.73 260.96
07:44:18 3 2.17 68.56 0.34 0.06 0.03 0.00 28.83 271.47

Report CPU utilization using sar command

You can display today’s CPU activity, with sar command:
# sar
Output:

Linux 2.6.9-42.0.3.ELsmp (dellbox.xyz.co.in) 01/13/2007

12:00:02 AM CPU %user %nice %system %iowait %idle
12:10:01 AM all 1.05 0.00 0.28 0.04 98.64
12:20:01 AM all 0.74 0.00 0.34 0.38 98.54
12:30:02 AM all 1.09 0.00 0.28 0.10 98.53
12:40:01 AM all 0.76 0.00 0.21 0.03 99.00
12:50:01 AM all 1.25 0.00 0.32 0.03 98.40
01:00:01 AM all 0.80 0.00 0.24 0.03 98.92
...
.....
..
04:40:01 AM all 8.39 0.00 33.17 0.06 58.38
04:50:01 AM all 8.68 0.00 37.51 0.04 53.78
05:00:01 AM all 7.10 0.00 30.48 0.04 62.39
05:10:01 AM all 8.78 0.00 37.74 0.03 53.44
05:20:02 AM all 8.30 0.00 35.45 0.06 56.18
Average: all 3.09 0.00 9.14 0.09 87.68

Comparison of CPU utilization

The sar command writes to standard output the contents of selected cumulative activity counters in the operating system. The accounting system, based on the values in the count and interval parameters. For example display comparison of CPU utilization; 2 seconds apart; 5 times, use:
# sar -u 2 5
Output (for each 2 seconds. 5 lines are displayed):

Linux 2.6.9-42.0.3.ELsmp (www1lab2.xyz.ac.in) 01/13/2007

05:33:24 AM CPU %user %nice %system %iowait %idle
05:33:26 AM all 9.50 0.00 49.00 0.00 41.50
05:33:28 AM all 16.79 0.00 74.69 0.00 8.52
05:33:30 AM all 17.21 0.00 80.30 0.00 2.49
05:33:32 AM all 16.75 0.00 81.00 0.00 2.25
05:33:34 AM all 14.29 0.00 72.43 0.00 13.28
Average: all 14.91 0.00 71.49 0.00 13.61

Where,

* -u 12 5 : Report CPU utilization. The following values are displayed:
o %user: Percentage of CPU utilization that occurred while executing at the user level (application).
o %nice: Percentage of CPU utilization that occurred while executing at the user level with nice priority.
o %system: Percentage of CPU utilization that occurred while executing at the system level (kernel).
o %iowait: Percentage of time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
o %idle: Percentage of time that the CPU or CPUs were idle and the system did not have an outstanding disk I/O request.

To get multiple samples and multiple reports set an output file for the sar command. Run the sar command as a background process using.
# sar -o output.file 12 8 >/dev/null 2>&1 &
Better use nohup command so that you can logout and check back report later on:
# nohup sar -o output.file 12 8 >/dev/null 2>&1 &

All data is captured in binary form and saved to a file (data.file). The data can then be selectively displayed ith the sar command using the -f option.
# sar -f data.file
Task: Find out who is monopolizing or eating the CPUs

Finally, you need to determine which process is monopolizing or eating the CPUs. Following command will displays the top 10 CPU users on the Linux system.
# ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
OR
# ps -eo pcpu,pid,user,args | sort -r -k1 | less
Output:

%CPU PID USER COMMAND
96 2148 vivek /usr/lib/vmware/bin/vmware-vmx -C /var/lib/vmware/Virtual Machines/Ubuntu 64-bit/Ubuntu 64-bit.vmx -@ ""
0.7 3358 mysql /usr/libexec/mysqld --defaults-file=/etc/my.cnf --basedir=/usr --datadir=/var/lib/mysql --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --skip-locking --socket=/var/lib/mysql/mysql.sock
0.4 29129 lighttpd /usr/bin/php
0.4 29128 lighttpd /usr/bin/php
0.4 29127 lighttpd /usr/bin/php
0.4 29126 lighttpd /usr/bin/php
0.2 2177 vivek [vmware-rtc]
0.0 9 root [kacpid]
0.0 8 root [khelper]

Now you know vmware-vmx process is eating up lots of CPU power. ps command displays every process (-e) with a user-defined format (-o pcpu). First field is pcpu (cpu utilization). It is sorted in reverse order to display top 10 CPU eating process.
iostat command

You can also use iostat command which report Central Processing Unit (CPU) statistics and input/output statistics for devices and partitions. It can be use to find out your system's average CPU utilization since the last reboot.
# iostatOutput:

Linux 2.6.15.4 (debian) Thursday 06 April 2006

avg-cpu: %user %nice %system %iowait %steal %idle
16.36 0.00 2.99 1.06 0.00 79.59

Device: tps Blk_read/s Blk_wrtn/s Blk_read Blk_wrtn
hda 0.00 0.00 0.00 16 0
hdb 6.43 85.57 166.74 875340 1705664
hdc 0.03 0.16 0.00 1644 0
sda 0.00 0.00 0.00 24 0

You may want to use following command, which gives you three outputs every 5 seconds (as previous command gives information since the last reboot):$ iostat -xtc 5 3
GUI tools for your laptops/desktops

Above tools/commands are quite useful on remote server. For local system with X GUI installed you can try out gnome-system-monitor. It allows you to view and control the processes running on your system. You can access detailed memory maps, send signals, and terminate the processes.
$ gnome-system-monitor

In addition, the gnome-system-monitor provides an overall view of the resource usage on your system, including memory and CPU allocation.

gnome-system-monitor - view and control the processes

Further readings

* For more information and command option please read man pages of top, iostat, mpstat, sar, ps commands.

Linux Limit CPU Usage Per Process

I don't want background process to eat all my CPU. I know how to find out CPU utilization but how do I limit the cpu usage of a process under Linux operating system? How do I force a process to limit itself to 25% only?

You can use cpulimit program that attempts to limit the cpu usage of a process. Limits are expressed in percentage and not in cpu time. cpulimit does not act on the nice value or other scheduling priority stuff, but on the real cpu usage. Also, it is able to adapt itself to the overall system load, dynamically and quickly.
Install cpulimit

Type the following commands to install latest stable release:
# cd /tmp
# wget 'http://downloads.sourceforge.net/cpulimit/cpulimit-1.1.tar.gz'
# tar cpulimit-1.1.tar.gz
# cd cpulimit-1.1
# make
# cp cpulimit /usr/local/sbin/
# rm -rf cpulimit*
A note about Debian / Ubuntu Linux users

Type the following command to install cpulimit:
$ sudo apt-get update
$ sudo apt-get install cpulimit
How do I use cpulimit?

To limit CPU usage of the process called firefox to 30%, enter:
# cpulimit -e firefox -l 30
To limit CPU usage of the process to 30% by using its PID, enter:
# cpulimit -p 1313 -l 30
To find out PID of the process use any of the following:
# ps aux | less
# ps aux | grep firefox
# pgrep -u vivek php-cgi
# pgrep lighttpd
You can also use absolute path name of the executable, enter:
# cpulimit -P /opt/firefox/firebox -l 30
Where,

* -p : Process PID.
* -e : Process name.
* -l : percentage of CPU allowed from 0 to 100.
* -P: absolute path name of the executable program file.

Root vs Normal User Account

From the project webpage:

cpulimit should run at least with the same user running the controlled process. But it is much better if you run cpulimit as root, in order to have a higher priority and a more precise control.

A Note About SMP (Multicore / MultiCpu) Systems

Again quoting from the project webpage:

If your machine has one processor you can limit the percentage from 0% to 100%, which means that if you set for example 50%, your process cannot use more than 500 ms of cpu time for each second. But if your machine has four processors, percentage may vary from 0% to 400%, so setting the limit to 200% means to use no more than half of the available power. In any case, the percentage is the same of what you see when you run top.

Related Throttling Utilities

1. ionice utility - Avoid sudden outburst of backup shell script / program disk I/O.
2. Limit disk I/O for rsync tool.
3. Linux nice command: Run Process With Modified Scheduling Priority ( nicenesses )
4. renice command: Change the Priority of a Already Running Process