返回介绍

C

发布于 2025-02-25 23:44:00 字数 2023 浏览 0 评论 0 收藏 0

%%file fib.h

double fib(int n);
Writing fib.h
%%file fib.c

double fib(int n) {
    double a = 0, b = 1;
    for (int i=0; i<n; i++) {
        double tmp = b;
        b = a;
        a += tmp;
     }
    return a;
}
Writing fib.c

Using bitey and clang

This is perhaps the simplest method, but it only works with the clang compiler and does not geenrate highly optimized code.

import bitey
!clang -O3 -emit-llvm -c fib.c -o fib1.o
import fib1

fib1.fib(100)
354224848179261997056.0000
%timeit fib1.fib(100)
1000000 loops, best of 3: 941 ns per loop

Using Cython

I recomment using Cython for all your C/C++ interface needs as it is highly optimized and can do boht C \(\rightarrow\) Python and Python \(\rightarrow\) C. It is a littel more involved, but the steps always follow the same template.

Define functions to be imported from C

%%file fib.pxd

cdef extern from "fib.h":
    double fib(int n)
Writing fib.pxd

Define wrapper for calling function from Python

%%file fib2.pyx

cimport fib

def fib(n):
    return fib.fib(n)
Writing fib2.pyx

Use distutils to compile shared library for Python

This is the standard way all Python modules are compiled for distribution, and results in a build that is portable over different platforms.

%%file setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize

ext = Extension("fib2",
              sources=["fib2.pyx", "fib.c"])

setup(name = "cython_fib",
      ext_modules = cythonize(ext))
Overwriting setup.py
! python setup.py build_ext -i &> /dev/null
import fib2

fib2.fib(100)
354224848179261997056.0000
%timeit fib2.fib(100)
1000000 loops, best of 3: 224 ns per loop

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文