Fred
Fred

Reputation: 1021

ctypes vs pure python

Why ctypes is slower in my code than pure python for to increment a variable ?

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

How to increase the speed with ctypes module ?

Upvotes: 2

Views: 574

Answers (1)

James Hopkin
James Hopkin

Reputation: 13973

The actual increment is a very simple operation and is unlikely to be taking most of the time. More likely it's the function calls themselves, and in the case of f2 you have the overhead of calling into ctypes.

Ctypes can provide performance gains by allowing you to implement non-trivial, CPU intensive parts of your program in C or C++.

Upvotes: 5

Related Questions