[Transfer] C code uses CPU L1 cache to calculate the number of prime numbers within one billion in one second

Last year I published an article using Python code + Numpy library + Sieve algorithm to calculate the number of prime numbers within 100 million in one second:

https://blog.csdn.net/Scott0902/article/details/128193368

Today I found on GitHub that a foreign expert has written a code in C language three years ago that uses the CPU L1 cache to perform ultra-high-speed calculations. If you have studied computer principles, you should know that the CPU's first-level cache is the fastest to read. Let alone 100 million, even prime numbers within one billion can be calculated in less than one second, which is simply the ceiling of computing performance!

Source code file name: sieve_eratosthenes.c

It should be noted that there is a printf statement in the segmented_sieve function to output prime numbers. The prime numbers will be printed continuously on the screen during runtime, so this line must be commented out, otherwise there will be a queue during runtime.

I compiled successfully using clang on Windows 10.

The first step when running:

You must first enter the L1 cache capacity of each thread of your CPU , in bytes. How to find this number? There are many methods. You can find it quickly by checking the task manager that comes with Win10, or by using professional tools such as CPU-Z and AIDA64.

Step 2: Enter the range, taking billions as an example, which is 1 followed by nine zeros.

I tried to enter 131072 in the first step, which is 128KB, and entered one billion in the second step. The calculation took: 1.434 seconds.

I tried adjusting the input value in the first step again and found that the larger the L1 cache input value, the longer the calculation takes, and the smaller the input value, the faster the calculation.

When the input value is 4096, the calculation takes the shortest time: only 0.816 seconds. The result of calculating the number of prime numbers is the same, which is jaw-droppingly fast!

I won’t post the code. If you are interested, please go to the awesome GitHub project address: https://github.com/TotallyNotChase/cFastSieve

Guess you like

Origin blog.csdn.net/Scott0902/article/details/134662294