限制CPU负载或设置进程属性 [英] Limit CPU load or set process prority

查看:70
本文介绍了限制CPU负载或设置进程属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是我第一次从主机收到太多的CPU负载警告.该代码只是一些带有mysql查询的随机php脚本,没有花哨的地方.(表并不是什么特别的表,最多几百行,如果有要求,我总是限制它们.

It's not the first time I get a too much cpu load warning from my hosting. The code is just some random php script with mysql queries, nothing fancy. (THe tables are nothing extraordinary, a few hundred lines maximum and I always limit them if requested.

我不介意它运行0.15秒而不是0.05秒,所以有什么方法可以控制进程优先级或限制CPU负载吗?

I don't mind if it runs for 0.15 second instead of 0.05, so is there a way I can control process priority or limit cpu load?

谢谢!

推荐答案

如果这是长时间运行的dameon或程序,请添加 sleep() / usleep() .睡眠不足会大大降低CPU使用率.

If this is a dameon or program that runs for long time add sleep()/usleep(). A small sleep will reduce your CPU usage dramatically.

以下代码将消耗大量的CPU

Following code will consume a lot of cpu

while(...){
//do stuff
}

因为您在这里没有给CPU腾出空间来执行其他任务.将其更改为

Because you are not giving room for CPU to do other task here. change it to

while(...){
   //do stuff
    sleep(1);
}

这将大大减少您的CPU使用率. 1秒的CPU占用大量时间来完成其他任务.

This will greatly decrease your CPU usage. 1 second for CPU is a lot of time to do other task.

要睡眠额外的 0.1 秒( 0.15-0.05 ),请使用usleep().

To sleep that extra 0.1 second (0.15 - 0.05) use usleep().

usleep(100000);

这篇关于限制CPU负载或设置进程属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆