基本函数的计时
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_primes(n: int) -> int:
count = 0
for k in range(2,n):
if is_prime(k):
count+=1
return count
%time [print(count_primes(1000000))]
执行结果
78498
CPU times: total: 4.17 s
Wall time: 4.18 s
taichi on x86 cpu
import taichi as ti
ti.init()
@ti.func
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
@ti.kernel
def count_primes(n: int) -> int:
count = 0
for k in range(2,n):
if is_prime(k):
count+=1
return count
%time [print(count_primes(100000000))]
执行结果
[Taichi] Starting on arch=x64
5761455
CPU times: total: 4min 5s
Wall time: 22.1 s
taichi on gpu rtx1060
import taichi as ti
ti.init(arch=ti.gpu)
@ti.func
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
@ti.kernel
def count_primes(n: int) -> int:
count = 0
for k in range(2,n):
if is_prime(k):
count+=1
return count
%time [print(count_primes(10000000))]
执行结果
[Taichi] Starting on arch=cuda
664579
CPU times: total: 453 ms
Wall time: 452 ms