c - 如何从 C 程序中获得 100% 的 CPU 使用率

这是一个非常有趣的问题,所以让我来设置一下场景。我在国家计算机博物馆工作,我们刚刚设法让一台 1992 年的 Cray Y-MP EL super 计算机运行起来,我们真的很想看看它的速度有多快!

我们认为最好的方法是编写一个简单的 C 程序来计算素数并显示计算所需的时间,然后在快速的现代台式 PC 上运行该程序并比较结果。

我们很快想出了这个代码来计算素数:

#include <stdio.h>
#include <time.h>

void main() {
    clock_t start, end;
    double runTime;
    start = clock();
    int i, num = 1, primes = 0;

    while (num <= 1000) { 
        i = 2; 
        while (i <= num) { 
            if(num % i == 0)
                break;
            i++; 
        }
        if (i == num)
            primes++;

        system("clear");
        printf("%d prime numbers calculated\n",primes);
        num++;
    }

    end = clock();
    runTime = (end - start) / (double) CLOCKS_PER_SEC;
    printf("This machine calculated all %d prime numbers under 1000 in %g seconds\n", primes, runTime);
}

在我们运行 Ubuntu(The Cray 运行 UNICOS)的双核笔记本电脑上运行良好,获得 100% 的 CPU 使用率,大约需要 10 分钟左右。回到家后,我决定在我的六核现代游戏 PC 上尝试一下,这就是我们遇到的第一个问题。

我首先将代码调整为在 Windows 上运行,因为这是游戏 PC 使用的,但很遗憾地发现该进程仅获得了 CPU 功率的 15% 左右。我想这一定是 Windows 就是 Windows,所以我启动到 Ubuntu 的 Live CD 中,认为 Ubuntu 将允许该进程像之前在我的笔记本电脑上那样充分发挥其潜力。

但是我只有 5% 的使用率!所以我的问题是,我怎样才能使程序在我的游戏机上以 100% 的 CPU 利用率在 Windows 7 或 Live Linux 上运行?另一件很棒但不是必需的事情是,最终产品是否可以是一个可以轻松分发并在 Windows 机器上运行的 .exe。

非常感谢!

附:当然,这个程序并不能真正与 Crays 8 专业处理器一起使用,那完全是另外一回事了……如果你知道如何优化代码以在 90 年代的 Cray super 计算机上运行,​​请给我们留言!

最佳答案

如果你想要 100% CPU,你需要使用超过 1 个核心。为此,您需要多个线程。

这是使用 OpenMP 的并行版本:

我不得不将限制增加到 1000000 以使其在我的机器上花费超过 1 秒。

#include <stdio.h>
#include <time.h>
#include <omp.h>

int main() {
    double start, end;
    double runTime;
    start = omp_get_wtime();
    int num = 1,primes = 0;

    int limit = 1000000;

#pragma omp parallel for schedule(dynamic) reduction(+ : primes)
    for (num = 1; num <= limit; num++) { 
        int i = 2; 
        while(i <= num) { 
            if(num % i == 0)
                break;
            i++; 
        }
        if(i == num)
            primes++;
//      printf("%d prime numbers calculated\n",primes);
    }

    end = omp_get_wtime();
    runTime = end - start;
    printf("This machine calculated all %d prime numbers under %d in %g seconds\n",primes,limit,runTime);

    return 0;
}

输出:

This machine calculated all 78498 prime numbers under 1000000 in 29.753 seconds

这是你的 100% CPU:

https://stackoverflow.com/questions/9244481/

相关文章:

linux - 如何删除 CLOSE_WAIT 套接字连接

linux - 我可以在已编译的二进制文件中更改 'rpath' 吗?

python - functools partial 是如何做到的?

linux - 在 printf 中使用颜色

python - 什么是字典 View 对象?

python - 我如何捕捉一个像异常一样的 numpy 警告(不仅仅是为了测试)?

linux - Git 和硬链接(hard link)

python - 为什么 apt-get 功能在 Mac OS X v10.9 (Mavericks

python - 类型错误 : Missing 1 required positional argu

linux - 使用 bash 历史记录获取先前的命令,复制它,然后 'run' 它但命令注释