我目前正在用 C 编写应用程序,我打算在其中模拟 ubuntu 中的 CPU 负载低于 100%。我使用阶乘算法来强调我的 CPU 和 nanosleep
函数来调节 CPU 使用率。目标是稳定的 CPU 使用率和合理的容差,可以逐步变化,即 20%、30% 等。问题是当我启动我的应用程序时,我得到的弹跳负载为 45-53%,这是我想要的负载50% CPU 使用率。由于我的研究,我需要获得稳定的 CPU 使用率,通过跟踪两次执行之间的时间戳来计算响应时间。
编辑 我正在使用 VmWare Workstation 和 Ubuntu 14.04 VM 进行研究。 这是代码
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
int main(void)
{
struct timeval t1;
int milisec = 5; // length of time to sleep, in miliseconds
struct timespec req = {0};
req.tv_sec = 0;
req.tv_nsec = milisec * 1000000L;
FILE *file;
file = fopen("trace.txt", "w");
//int j = 0;
while(1)
{
gettimeofday(&t1, NULL);
int i;
int res = 1;
for(i = 0; i < 580000; i++)
{
res = res*i;
}
nanosleep(&req, (struct timespec *)NULL);
fprintf(file, "%llu%llu\n", (unsigned long long)t1.tv_sec, (unsigned long long)t1.tv_usec);
fflush(file);
//j++;
}
}
最佳答案
这是我的看法 - 在我的灯光测试中似乎相当不错。基本思想是使用 getrusage
来跟踪程序拥有多少 CPU 时间,将其除以挂钟耗时,如果超过目标比率则得出结果。您可以看看它是否提供比您自己的代码更稳定的结果。
(注意:问题最初被标记为 C++ 而不是 C...代码可以轻松移植到 C)
#include <iostream>
#include <sstream>
#include <sys/time.h>
#include <sys/resource.h>
void usage_exit(const char* argv0)
{
std::cerr << "usage " << argv0 << " <target>\n"
" spin burning <target> proportion of one CPU (e.g. 0.5 = 50%)\n";
exit(1);
}
int main(int argc, const char* argv[])
{
if (argc != 2)
usage_exit(argv[0]);
std::istringstream iss(argv[1]);
double target;
if (!(iss >> target))
usage_exit(argv[0]);
struct timeval start, now;
gettimeofday(&start, 0);
struct rusage usage;
while (getrusage(RUSAGE_SELF, &usage) == 0)
{
gettimeofday(&now, 0);
double running = usage.ru_utime.tv_sec + usage.ru_utime.tv_usec * 1E-6 +
usage.ru_stime.tv_sec + usage.ru_stime.tv_usec * 1E-6;
double elapsed = now.tv_sec - start.tv_sec +
now.tv_usec * 1E-6 - start.tv_usec * 1E-6;
if (running / elapsed > target)
pthread_yield();
}
}
关于c - CPU使用不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30705010/