Codon是一个高性能的Python编译器,它将Python代码编译为本机机器代码,没有任何运行时开销。在单个线程上,Python 的典型加速大约是 10-100 倍或更多。Codon的性能通常与C/C++相当(有时甚至更好)。与Python不同,Codon支持本机多线程,这可以导致加速很多倍。Codon源于Seq项目。
适用于 Linux (x86_64) 和 macOS(x86_64 和 arm64)的预构建二进制文件随每个版本一起提供。下载并安装:
/bin/bash -c "$(curl -fsSL https://exaloop.io/install.sh)"
或者,你可以从源代码构建。
Codon是一种与Python兼容的语言,许多Python程序只需很少的修改即可工作:
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
编译器有许多选项和模式:
codon
# compile and run the program
codon run fib.py
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
# compile and run the program with optimizations enabled
codon run -release fib.py
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
# compile to executable with optimizations enabled
codon build -release -exe fib.py
./fib
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
# compile to LLVM IR file with optimizations enabled
codon build -release -llvm fib.py
# outputs file fib.ll
有关更多选项和示例,请参阅文档。
这个主要计数示例展示了Codon的OpenMP支持,通过添加一行即可启用。注释告诉编译器并行化以下 -循环,在本例中,使用动态计划、块大小为 100 和 16 个线程。
@par
for
from sys import argv
def is_prime(n):
factors = 0
for i in range(2, n):
if n % i == 0:
factors += 1
return factors == 0
limit = int(argv[1])
total = 0
@par(schedule='dynamic', chunk_size=100, num_threads=16)
for i in range(2, limit):
if is_prime(i):
total += 1
print(total)
密码子支持编写和执行GPU内核。下面是一个计算曼德布洛特集合的示例:
import gpu
MAX = 1000 # maximum Mandelbrot iterations
N = 4096 # width and height of image
pixels = [0 for _ in range(N * N)]
def scale(x, a, b):
return a + (x/N)*(b - a)
@gpu.kernel
def mandelbrot(pixels):
idx = (gpu.block.x * gpu.block.dim.x) + gpu.thread.x
i, j = divmod(idx, N)
c = complex(scale(j, -2.00, 0.47), scale(i, -1.12, 1.12))
z = 0j
iteration = 0
while abs(z) <= 2 and iteration < MAX:
z = z**2 + c
iteration += 1
pixels[idx] = int(255 * iteration/MAX)
mandelbrot(pixels, grid=(N*N)//1024, block=1024)
GPU 编程也可以使用 .
@par
@par(gpu=True)
虽然Codon支持几乎所有的Python语法,但它不是一个直接的替代品,大型代码库可能需要修改才能通过Codon编译器运行。例如,Python的一些模块尚未在Codon中实现,并且不允许使用Python的一些动态功能。密码子编译器生成详细的错误消息,以帮助识别和解决任何不兼容性。
密码子可以通过@codon.jit装饰器
在更大的Python代码库中使用。普通的Python函数和库也可以通过Python互操作性从Codon内部调用。
有关深入的文档,请参阅 docs.exaloop.io。