如果您想生成任意CPU负载或CPU利用率,我不太了解。是的,它们确实是不同的东西。我会尽力解决这两个问题。
首先: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使用率是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的答案中使用该程序。