c - 一台电脑有多少处理能力

标签 c linux process terminal cpu-usage

<分区>

我有以下代码,我在终端中运行。 在另一个终端中,我打开了“top”,在那里我可以看到我创建的新进程的 %CPU。我为进程数 (N) 运行它; 2、4、8、16。 每个我报告的平均 %CPU 是.. 2 - 100% 4 - 97% 8 - 50% 16 - 25%

如何根据这些结果确定计算机的处理能力?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define N 2 /* define the total number of processes we want */

/* Set global variable */
float total=0;

/* compute function just does something. */
int compute()
{
    int i;
    float oldtotal=0, result=0;

 /* for a large number of times just square root and square
 the arbitrary number 1000 */
    for(i=0;i<2000000000;i++)
    {
        result=sqrt(1000.0)*sqrt(1000.0);
    }
 /* Print the result – should be no surprise */
printf("Result is %f\n",result);

 /* We want to keep a running total in the global variable total */
    oldtotal = total;
    total = oldtotal + result;

 /* Print running total so far. */
    printf("Total is %f\n",total);
 return(0);
}

int main()
{
    int pid[N], i, j;
    float result=0;
    printf("\n"); /* bit of whitespace */

 /* We want to loop to create the required number of processes
 Note carefully how only the child process is left to run */
    for(i=0;i<N;i++)
    {
 /* Do the fork and catch it if it/one fails */
        if((pid[i]=fork())==-1)
    {
        exit(1);
    }

 /* now with child we want to do our computation */
    else if(pid[i] > 0)
    {
 /* give a message about the proc ID */
        printf("Process Id for process %d is %d\n",i,getpid());
 /* call the function to do some computation. If we used sleep
 The process would simply sleep. We do not want that */
            compute();
 /* After we have done our computation we must quit the for
 loop otherwise we get a fork bomb! */
            break;
        }
    }
  /* nothing else to do so end main function (and program) */
 return 0;
}

最佳答案

这取决于您对处理能力的定义。经典方法是每秒指令数 (MIPS) 或每秒浮点运算数 (FLOP)。

查找 MIPS 很棘手,因为在 C 代码中您不知道每行代码代表多少条指令。

不过,您可以进行百万级的计算。在 C 中循环执行随机数的 float * float 操作。查看进行大量计算需要多长时间(例如 109),然后计算您在一秒钟内完成了多少次。

然后乘以您拥有的处理器数量。

关于c - 一台电脑有多少处理能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28975791/

相关文章:

c++ - cudaMalloc()是否将数组初始化为0?

linux - 使用 printf 格式化不均匀的列表

java - ProcessBuilder调试

Python:进程运行的时间

winapi - Win32 进程如何获取其父进程的 pid?

c - read() 系统调用页面错误不依赖于文件大小

c - 如何将默认名称设置为 GtkComboBox?

c - 如何从 C 调用 MATLAB 代码?

linux - 带有 fftwf_plan_dft_r2c_1d 的库?

linux - 与 "[" "]"的字符串连接导致 shell 脚本中的 0