Skip to main content

一个将python函数翻译为c++函数并运行的jit编译器

Project description

l0n0lc

将 Python 函数翻译为 C++ 并运行的 JIT 编译器

Python Version License Version Zero Dependencies


简介

l0n0lc 是一个零外部依赖的 Python JIT 编译器,通过简单的装饰器将 Python 函数转换为原生 C++ 代码并编译执行。它专注于计算密集型任务的性能优化,同时保持 API 的简洁性和易用性。

核心特点

  • 零依赖 - 仅依赖 Python 3.10+ 标准库
  • 简单易用 - 一个 @jit 装饰器即可启用
  • 智能缓存 - 基于源码哈希,自动避免重复编译
  • 跨平台 - 支持 Linux、macOS、Windows
  • 类型推断 - 自动推断变量类型,生成高效 C++ 代码

安装

pip install l0n0lc

系统要求

  • Python 3.10 或更高版本
  • C++ 编译器(g++、clang++ 或 c++)
# Ubuntu/Debian
sudo apt install g++

# macOS
xcode-select --install

# Windows (MSYS2)
pacman -S mingw-w64-x86_64-gcc

快速开始

基础用法

from l0n0lc import jit

@jit()
def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

print(fibonacci(40))  # 输出: 102334155

容器类型支持

from typing import List

@jit()
def sum_list(nums: List[int]) -> int:
    total = 0
    for num in nums:
        total += num
    return total

print(sum_list([1, 2, 3, 4, 5]))  # 输出: 15

类支持

# 定义类(类本身不需要 jit 装饰器)
class Point:
    x: float
    y: float

    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

@jit()
def compute_distance() -> float:
    # 在 JIT 函数内部创建和使用类实例
    p1 = Point(0.0, 0.0)
    p2 = Point(3.0, 4.0)
    dx = p1.x - p2.x
    dy = p1.y - p2.y
    return (dx * dx + dy * dy) ** 0.5

print(compute_distance())  # 输出: 25.0 (平方距离)

API 参考

@jit 装饰器

@jit(
    总是重编=False,        # 强制重新编译
    可执行文件名=None,     # 编译为独立可执行文件
    优化级别="-O3",        # C++ 优化级别
    启用_lto=False,        # 启用链接时优化
    启用_simd=False,       # 启用 SIMD 优化
)
def function_name() -> ReturnType:
    ...

中文别名

from l0n0lc import jit, 即时编译

# 两者等价
@jit()
def func1(): pass

@即时编译()
def func2(): pass

高级功能

AOT 编译

# 将 Python 文件编译为独立可执行文件
l0n0lc-aot-compile input.py -o output_executable

自定义 C++ 映射

import l0n0lc as lc

# 映射到 C++ 标准库函数
@lc.映射函数到('sqrt({x})', ['<cmath>'])
def my_sqrt(x: float) -> float:
    return 0  # 实际使用 C++ 实现

性能优化选项

# 启用 LTO 优化
@jit(启用_lto=True)
def optimized_function():
    pass

# 启用 SIMD
@jit(启用_simd=True)
def vectorized_compute(data: List[float]) -> List[float]:
    pass

工作原理

Python 函数
    ↓
AST 解析与类型推断
    ↓
C++ 代码生成
    ↓
系统 C++ 编译器
    ↓
动态库 (.so/.dll/.dylib)
    ↓
ctypes 加载执行

性能对比

import time
from l0n0lc import jit

def fib_py(n: int) -> int:
    if n <= 1:
        return n
    return fib_py(n-1) + fib_py(n-2)

@jit()
def fib_jit(n: int) -> int:
    if n <= 1:
        return n
    return fib_jit(n-1) + fib_jit(n-2)

# 测试
n = 35

t = time.time()
fib_py(n)
py_time = time.time() - t

t = time.time()
fib_jit(n)
jit_time = time.time() - t

print(f"Python: {py_time:.3f}s")
print(f"JIT:    {jit_time:.3f}s")
print(f"加速比: {py_time/jit_time:.1f}x")

支持的语言特性

特性 支持情况
基本类型 (int, float, bool, str)
容器类型 (List, Dict, Set)
类定义和实例方法
for/while 循环
if/else 条件
try/except 异常处理
列表推导式
可变参数 (*args, **kwargs)
生成器
异步函数

开发

从源码构建

git clone https://github.com/username/l0n0lc.git
cd l0n0lc
pip install -e .

运行测试

cd tests
for test in test_*.py; do
    echo "Running $test"
    python "$test"
done

构建发布包

# 使用 uv 构建
uv build

# 或使用构建脚本
./build.sh

缓存机制

编译产物存储在 l0n0lcoutput/ 目录:

l0n0lcoutput/
├── {hash}_{filename}_{funcname}@_{hash}.cpp  # C++ 源码
├── {hash}_{filename}_{funcname}@_{hash}.h    # 头文件
└── {hash}_{filename}_{funcname}@_{hash}.so   # 动态库

缓存基于函数源码的 BLAKE2s 哈希,代码修改后自动重新编译。

清理缓存

# 清理所有缓存
rm -rf l0n0lcoutput/

# 清理构建产物
./build.sh  # 自动清理并重新构建

项目结构

l0n0lc/
├── 即时编译.py          # @jit 装饰器
├── Py转Cpp转译器.py     # AST 转 C++ 核心逻辑
├── cpp编译器.py         # C++ 编译器管理
├── 运行时加载.py        # ctypes 加载
├── cpp类型.py           # C++ 类型定义
├── 类型转换.py          # Python ↔ C++ 类型转换
├── std_vector.py        # std::vector 支持
├── std_map.py           # std::map 支持
├── std_set.py           # std::set 支持
├── aot编译.py           # AOT 编译
├── simd优化.py          # SIMD 优化
├── 并行编译器.py        # 并行编译
└── ...

限制与注意事项

  1. 类型注解 - 建议提供完整的类型注解以提高代码质量
  2. 首次编译 - 首次调用会有编译延迟,后续调用使用缓存
  3. 适用场景 - 适合计算密集型任务,简单函数可能因编译开销反而变慢
  4. 函数名编码 - 包含非 ASCII 字符的函数名会被编码

许可证

MIT License


作者

倾城铸剑师


文档

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

l0n0lc-1.0.1.tar.gz (121.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

l0n0lc-1.0.1-py3-none-any.whl (99.3 kB view details)

Uploaded Python 3

File details

Details for the file l0n0lc-1.0.1.tar.gz.

File metadata

  • Download URL: l0n0lc-1.0.1.tar.gz
  • Upload date:
  • Size: 121.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.4

File hashes

Hashes for l0n0lc-1.0.1.tar.gz
Algorithm Hash digest
SHA256 9ab1b1a5bc5dba8515e65a782098447f08c80068e388618dacfc7038d9a4c5a9
MD5 ec7ea45c478f82c3fb0535e2a0f3f28f
BLAKE2b-256 aa6853c3241ca0f9e15df55a3a540c3bf47c0b1565b94a493be45179bf351dd0

See more details on using hashes here.

File details

Details for the file l0n0lc-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: l0n0lc-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 99.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.4

File hashes

Hashes for l0n0lc-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6ce1f0584c744ef4027522914a7e504e74eb45d9a0b5f92e6bb41d8d9ae98a61
MD5 66b55f2e6fb30493385261b5fb91a1eb
BLAKE2b-256 fc10033ffe40d98f20f2ff4b866c004dccfaabbef40f5cfe7c1d7d5e8b2a2f63

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page