加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux:如何加载系统内存?

发布时间:2020-12-14 01:38:35 所属栏目:Linux 来源:网络整理
导读:我正在开发一个小功能,它可以让我的用户了解CPU的占用情况. 我正在使用cat / proc / loadavg,它返回众所周知的3个数字. 我的问题是,当我正在开发时,CPU现在没有做任何事情. 有没有一种很好的方法来在CPU上产生som负载,我想的是类似于makecpudosomething 30,
我正在开发一个小功能,它可以让我的用户了解CPU的占用情况.
我正在使用cat / proc / loadavg,它返回众所周知的3个数字.

我的问题是,当我正在开发时,CPU现在没有做任何事情.

有没有一种很好的方法来在CPU上产生som负载,我想的是类似于makecpudosomething 30,负载为0.3或类似.这样的应用程序是否存在?

另外,有没有办法以受控方式吃掉RAM?

谢谢

迈克尔

解决方法

如果你想生成任意的 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 <stdlib.h>
#include <unistd.h>
#include <err.h>
#include <math.h>
#include <sys/time.h>
#include <stdarg.h>
#include <sys/wait.h>

#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答案中的程序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读