1
votes

i wrote a simple python code that just prints prime numbers nonstop but it only uses 25% percent of my laptops cpu (100% of a single core) . but i want it to use all of the cores. is that possible? BTW here is the code:

x = 10
while True:
    for num in range(1, x):
        flag = False
        if x > 1:
            for i in range(2, x):
                if (x % i) == 0:
                    flag = True
                    break
        if not flag:
            print(x, "is a prime number")
            break
    x += 1
1
You are using a single thread software. It can only utilize 100% for a single core on your system. - user56700
It happily eats 100% of 1 core (CPU) on my machine. - AKX
I initially tried with macOS, and now in a Linux VM. Same result: eats 100% of 1 CPU. - AKX
This algorithm is fairly easily parallelizable: just split the range (1..x) is parts, with each core checking a subrange. But it's not that easy in Python. - MSalters
@MSalters It's not like it's very difficult either, but it doesn't make much sense to try and parallelize such a naive algorithm. - AKX

1 Answers

0
votes

This begs the question: how did you measure how much CPU your program uses?

Here's a screenshot from my macOS machine, running your program:

enter image description here

And here, a screenshot from htop on a Linux virtual machine:

enter image description here

In other words, your program will happily consume as much of a single CPU core as it can, as it's single-threaded.