您的位置:首页 > 理论基础 > 计算机网络

【转】Linux系统下使用程序控制CPU占用率、内存占用率、网络带宽占用率的方法

2013-05-07 21:44 751 查看
转自:http://dzmailbox.blog.163.com/blog/static/12053438520121752313440/

1. 模拟高CPU占用率

首先写一个C++程序,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>

int main()
{
int timeuse=0;
struct timeval tpstart,tpend;
while (1)
{
gettimeofday(&tpstart,NULL);
while (1)
{
gettimeofday(&tpend,NULL);
timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_usec - tpstart.tv_usec);
timeuse /= 1000;
}

sleep(20 / 1000);
}

return 0;
}
保存成cpuratio.c文件,然后执行g++ -o cpuratio cpuratio.c编译,编译成功后生成可执行文件cpuratio
执行./cpuratio &
然后使用top命令或vmstat 1命令来观察相应进程的CPU占用率,没有达到预期目标的话就多执行几次。
另外,介绍一款可以限制软件CPU占用率的开源软件,cpulimiter。可以限制程序使用CPU的百分比,而不是时间。
svn checkout https://cpulimit.svn.sourceforge.net/svnroot/cpulimit/trunk cpulimit
cd cpulimit
./configure
make
然后执行./cpulimit --exe cpuratio --limit 80

则可以限制cpuratio进程的cpu占用率为80%

2. 模拟高内存占用率

还是写一个程序,循环申请变量耗尽内存:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>

int main()
{
int timeuse=0;
struct timeval tpstart,tpend;
while (1)
{
gettimeofday(&tpstart,NULL);
while (1)
{
gettimeofday(&tpend,NULL);
timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_usec - tpstart.tv_usec);
timeuse /= 1000;
char * Logmsg = new char[65535];
}

sleep(20 / 1000);
}

return 0;
}
保存成eatmem.c,编译后执行。然后使用top观察剩余内存,是不是刷刷的掉啊。
想停止这个程序的话就按ctrl+c,剩余内存就回来了。

3. 模拟高网络带宽占用率

这个需要下载一个工具:iperf
http://sourceforge.net/projects/iperf下载,然后编译安装到两台服务器上,一个做客户端一个做服务器
服务器端执行./iperf -u -s
客户端执行./iperf -u -c xxx.xxx.xxx.xxx(你的IP) -b 100M -i 1 -w 1M -t 600
其中-b后面跟的100M指占用100Mbits带宽。不过实际运行时不一定很准确,可以适当提高。运行之后就能看到实时的网络带宽占用情况。-t 600代表执行600秒。其他我也不懂,哈哈~

如果你想自己查看网卡的流量,也可以用下面这个shell脚本来看:
#!/bin/bash
echo -n "请输入需要查询的网卡的接口:"
read eth
echo "你要查询的网卡接口为"$eth
echo -n "输入需要等到的时间(秒):"
read sec
echo "你计算的是"$sec"秒内的平均流量"
infirst=$(awk '/'$eth'/{print $1 }' /proc/net/dev |sed 's/'$eth'://')
outfirst=$(awk '/'$eth'/{print $10 }' /proc/net/dev)
sumfirst=$(($infirst+$outfirst))
sleep $sec"s"
inend=$(awk '/'$eth'/{print $1 }' /proc/net/dev |sed 's/'$eth'://')
outend=$(awk '/'$eth'/{print $10 }' /proc/net/dev)
sumend=$(($inend+$outend))
sum=$(($sumend-$sumfirst))
echo $sec"秒内总流量为:"$sum"bytes"
aver=$(($sum/$sec))
echo "平均流量为:"$aver"bytes/sec"

把上面的文件存成netflow.sh文件,然后执行就可以看到一段时间内的网络流量了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐