ctypes vs纯python

Fre*_*red 2 python performance ctypes

为什么ctypes在我的代码中比纯python更慢以增加变量?

from ctypes import *
import timeit

def f1():
    global t
    t += 1

def f2():
    p[0] += 1

t = 0
n = c_int(0)
p = pointer(n)

print(timeit.timeit("f1()", setup="from __main__ import f1")) # 0.3417885800008662
print(timeit.timeit("f2()", setup="from __main__ import f2")) # 0.5280102270189673

print(t) # 1000000
print(n.value) # 1000000
Run Code Online (Sandbox Code Playgroud)

如何用ctypes模块提高速度?

Jam*_*kin 5

实际的增量是一个非常简单的操作,并且大部分时间都不太可能.更有可能的是函数调用自己,并且在f2你遇到调用ctypes的开销的情况下.

Ctypes可以通过允许您在C或C++中实现程序的非平凡,CPU密集型部分来提供性能提升.