使用 C 代码提高 CPU 利用率并将其保持在一定水平
我正在编写一个C代码(在Linux上),运行时需要消耗一定量的CPU。我正在进行一项实验,在达到某个 CPU 阈值时触发某些操作。因此,一旦利用率达到某个阈值,我需要将其保持在该状态 30 秒,直到完成实验。我正在使用 top 命令监视 CPU 利用率。
所以我的问题是 - 1. 如何将 CPU 利用率提高到给定值(如果可能,以确定的方式)? 2. 一旦达到阈值,有没有办法在预定时间内将其保持在该水平?
top 命令的示例输出(第 9 列是“top”进程使用的 CPU)- 19304 abcde 16 0 5448 1212 808 R 0.2 0.0 0:00.06 top
与上面类似,我将查看顶部的行,它显示了我的二进制文件的利用率。
任何帮助将不胜感激。另外,如果您需要更多详细信息,请告诉我。
谢谢!
编辑: 下面的代码行让我可以很好地控制 CPU 利用率 - 在下面的情况下,我有 2 个选择 - 将其保持在 50% 以上和保持在 50% 以下 - 经过一些尝试和错误,我在给定的 usleep 值上安定下来。
endwait = clock() + ( seconds * CLOCKS_PER_SEC );
while( clock() < endwait ) {}
if (cpu_utilization > 50)
usleep(250000);
else
usleep(700000);
希望这有帮助!
I am writing a C code (on Linux) that needs to consume a certain amount of CPU when it's running. I am carrying out an experiment in which I trigger certain actions upon reaching a certain CPU threshold. So, once the Utilization reaches a certain threshold, I need to keep it at that state for say 30 seconds till I complete my experiments. I am monitoring the CPU Utilization using the top command.
So my questions are -
1. How do I increase the CPU Utilization to a given value (in a deterministic way if possible)?
2. Once I get to the threshold, is there a way to keep it at that level for a pre-defined time?
Sample output of top command (the 9th column is CPU used by the 'top' process) -
19304 abcde 16 0 5448 1212 808 R 0.2 0.0 0:00.06 top
Similar to above, I will look at the line in top which shows the utilization of my binary.
Any help would be appreciated. Also, let me know if you need more details.
Thanks!
Edit:
The following lines of code allowed me to control CPU Utilization quite well - In the following case, I have 2 options - keep it above 50% and keep it below 50% - After some trial and error, I settled down at the given usleep values.
endwait = clock() + ( seconds * CLOCKS_PER_SEC );
while( clock() < endwait ) {}
if (cpu_utilization > 50)
usleep(250000);
else
usleep(700000);
Hope this helps!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
cpuburn 已知会使 CPU 利用率如此之高,从而提高其温度达到最高水平。
似乎没有更多关于它的官方网站,但您仍然可以使用 Debian package< 访问源代码/a> 或 谷歌代码。
它是用 asm 实现的,所以你必须做一些粘合才能在 C 中与它交互。
cpuburn is known to make CPU utilization so high that it raise its temperature to its max level.
It seems there is no more official website about it, but you can still access to source code with Debian package or googlecode.
It's implemented in asm, so you'll have to make some glue in order to interact with it in C.
在我看来,此类东西应该具有恒定的 CPU 利用率:
md5和< /dev/urandom
Something of this sort should have a constant CPU utilization, in my opinion:
md5sum < /dev/urandom