如果你想生成任意的
CPU load or CPU utilization,我不太了解.是的,它们确实是不同的东西.我会尽力解决这两个问题.
首先:load是在给定时间内运行,可运行或等待cpu调度程序队列的平均进程数,“想要你的cpu的那个”可以这么说.
因此,如果要生成任意负载(比如0.3),则必须在30%的时间内运行一个进程,然后在70%的时间内将其从运行队列中删除,将其移至休眠队列或将其终止,例如.
您可以尝试使用此脚本执行此操作:
export LOAD=0.3
while true
do yes > /dev/null &
sleep $LOAD
killall yes
sleep `echo "1 - $LOAD" | bc`
done
请注意,您必须等待一段时间(1分钟,10分钟和15分钟)才能获得相应的数字,并且它将受到系统中其他进程的影响.系统越繁忙,这个数字就越漂浮.最后一个数字(间隔15分钟)往往是最准确的.
相反,CPU usage是cpu用于处理计算机程序指令的时间量.
因此,如果要生成任意cpu使用率(比如说30%),则必须运行30%的cpu占用流程并占用70%的流程.
我写了一个例子来告诉你:
#include
#include
#include
#include
#include
#include
#include
#define cpuUSAGE 0.3 /* set it to a 0 < float < 1 */
#define PROCESSES 1 /* number of child worker processes */
#define CYCLETIME 50000 /* total cycle interval in microseconds */
#define WORKTIME (CYCLETIME * cpuUSAGE)
#define SLEEPTIME (CYCLETIME - WORKTIME)
/* returns t1-t2 in microseconds */
static inline long timediff(const struct timeval *t1,const struct timeval *t2)
{
return (t1->tv_sec - t2->tv_sec) * 1000000 + (t1->tv_usec - t2->tv_usec);
}
static inline void gettime (struct timeval *t)
{
if (gettimeofday(t,NULL) < 0)
{
err(1,"Failed to acquire time");
}
}
int hogcpu (void)
{
struct timeval tWorkStart,tWorkCur,tSleepStart,tSleepStop;
long usSleep,usWork,usWorkDelay = 0,usSleepDelay = 0;
do
{
usWork = WORKTIME - usWorkDelay;
gettime (&tWorkStart);
do
{
sqrt (rand ());
gettime (&tWorkCur);
}
while ((usWorkDelay = (timediff (&tWorkCur,&tWorkStart) - usWork)) < 0);
if (usSleepDelay <= SLEEPTIME)
usSleep = SLEEPTIME - usSleepDelay;
else
usSleep = SLEEPTIME;
gettime (&tSleepStart);
usleep (usSleep);
gettime (&tSleepStop);
usSleepDelay = timediff (&tSleepStop,&tSleepStart) - usSleep;
}
while (1);
return 0;
}
int main (int argc,char const *argv[])
{
pid_t pid;
int i;
for (i = 0; i < PROCESSES; i++)
{
switch (pid = fork ())
{
case 0:
_exit (hogcpu ());
case -1:
err (1,"fork Failed");
break;
default:
warnx ("worker [%d] forked",pid);
}
}
wait(NULL);
return 0;
}
如果您想吃掉固定数量的RAM,可以使用cgkanchi答案中的程序.