gpt4 book ai didi

python - ctypes 与纯 python

转载 作者:行者123 更新时间:2023-11-28 21:48:38 27 4
gpt4 key购买 nike

为什么 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

如何使用 ctypes 模块提高速度?

最佳答案

实际增量是一个非常简单的操作,不太可能占用大部分时间。更有可能是函数调用本身,在 f2 的情况下,您有调用 ctypes 的开销。

Ctypes 允许您使用 C 或 C++ 实现程序中重要的 CPU 密集型部分,从而提高性能。

关于python - ctypes 与纯 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952851/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com