How to get 100% CPU usage from a C program

前端 未结 9 2557
半阙折子戏
半阙折子戏 2020-11-27 10:12

This is quite an interesting question so let me set the scene. I work at The National Museum of Computing, and we have just managed to get a Cray Y-MP EL super computer from

9条回答
  •  天涯浪人
    2020-11-27 10:57

    If you want 100% CPU, you need to use more than 1 core. To do that, you need multiple threads.

    Here's a parallel version using OpenMP:

    I had to increase the limit to 1000000 to make it take more than 1 second on my machine.

    #include 
    #include 
    #include 
    
    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;
    }
    

    Output:

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

    Here's your 100% CPU:

    enter image description here

提交回复
热议问题