返回介绍

Using functions from various compiled languages in Python

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

There are 2 main reasons why interpreted Python code is slower than code in a compiled lanauge such as C (or other compiled langauge):

  • Python executes byte code in a virtual machine (minor effect) while C compiles down to machine instructions specific for the processor
  • Python has dynamic typing (major effect) while C is statically typed. In a dynamically typed language, the simple expression a + b can mean many, many different things, and the interrpeter has to figure out which interpretation is intended. In contrast, a and b must have a type in C such as double and there is no ambiguity about what + means to resolve.

If speed is critical, it is often necessary to exploit the efficiency of compiled languges - this can be done while retaining the nice features of Python in 2 directions

  • From C to Python
  • From Python to C

Here we will look at how to go from C (C++, Fortran, Julia) to Python,

def python_fib(n):
    a, b = 0,  1
    for i in range(n):
        a, b = a+b, a
    return a
%timeit python_fib(100)
100000 loops, best of 3: 8.47 µs per loop

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

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

发布评论

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