安装
目前只linux和mac系统。从https://github.com/exaloop/codon下载最新版进行安装。然后设置环境变量:
export PATH=~/.codon/bin:$PATH
export CODON_PYTHON=/usr/lib/libpython3.10.so
上述路径换成自己的系统路径。下面的示例代码(goldbach.codon
):
import math
def prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
n = 100_000
primes = [i for i in range(2, n) if prime(i)]
for i in primes:
for j in primes:
if i < j and i + j == n:
print(f"{n} = {i} + {j}")
编译并运行程序:
codon build goldbach.codon --release
./goldbach
速度明显比原始的python程序快很多。下面的代码plot.codon
使用mathplotlib进行绘图:
from python import numpy as np
from python import matplotlib.pyplot as plt
# Set chinese font family
# 在linux上可用:
# $ fc-list :lang=zh family
# 检查支持中文的所有字体
plt.rcParams["font.family"] = ["Source Han Sans CN"]
# Fixing random state for reproducibility
np.random.seed(19680801)
# Compute pie slices
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
colors = plt.cm.viridis(radii / 10.0)
ax = plt.subplot(projection="polar")
ax.bar(theta, radii, width=width, bottom=0.0, color=colors, alpha=0.5)
ax.set_title("极坐标图")
plt.show()
编译并运行:
codon build plot.codon --release
./plot
结果运行正常。
标签:LLVM,python,random,codon,radii,编译器,plt,np From: https://www.cnblogs.com/soarowl/p/17441456.html