Backend Development 4 min read

How Taichi Accelerates Prime Counting by 200× Over Pure Python

This article demonstrates how the Taichi library can speed up a Python prime‑counting program by roughly two hundred times compared to the unoptimized version and five times faster than using Numba, providing clear code examples and performance results.

Model Perspective
Model Perspective
Model Perspective
How Taichi Accelerates Prime Counting by 200× Over Pure Python

Previously I mentioned using the numba library to accelerate Python; here I introduce another acceleration library, taichi .

First, we write a function to count the number of primes within a given range:

<code>def is_prime(n:int):
    result = True
    for k in range(2, int(n**0.5)+1):
        if n % k == 0:
            result = False
            break
    return result

def count_prime(n:int) -> int:
    count = 0
    for k in range(2, n):
        if is_prime(k):
            count += 1
    return count</code>

Running the normal (non‑accelerated) version on my computer to count primes between 0 and 10 million takes:

2 minutes 10 seconds.

Using Taichi for acceleration:

<code>import taichi as ti
ti.init()

@ti.func
def is_prime1(n:int):
    result = True
    for k in range(2, int(n**0.5)+1):
        if n % k == 0:
            result = False
            break
    return result

@ti.kernel
def count_prime1(n:int) -> int:
    count = 0
    for k in range(2, n):
        if is_prime1(k):
            count += 1
    return count

print(count_prime1(10000000))</code>

Time taken:

1.09 seconds, about a 200× speedup.

Now using numba for acceleration:

<code>from numba import jit
@jit(nopython=True)
def is_prime2(n:int):
    result = True
    for k in range(2, int(n**0.5)+1):
        if n % k == 0:
            result = False
            break
    return result

@jit(nopython=True)
def count_prime2(n:int) -> int:
    count = 0
    for k in range(2, n):
        if is_prime2(k):
            count += 1
    return count

print(count_prime2(10000000))</code>

Time taken:

5 seconds. Thus Taichi is about five times faster than Numba for this problem – impressive!

Reference

https://tech.sina.com.cn/csj/2022-09-09/doc-imqqsmrn8434391.shtml

PerformanceOptimizationPythonTaichiNumbaPrime Counting
Model Perspective
Written by

Model Perspective

Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.