Performance analysis of Python built-in type programs

timeit module

The timeit module can be used to test the execution speed of a small piece of Python code.

class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)

Timer is a class that measures the execution speed of small pieces of code.

The stmt parameter is the code statement to be tested (statment);

The setup parameter is the setting required to run the code;

The timer parameter is a timer function, which is platform-dependent.

timeit.Timer.timeit(number=1000000)

An object method in the Timer class that tests the execution speed of a statement. The number parameter is the number of tests when testing the code, the default is 1000000 times. The method returns the average time spent executing the code, as a float in seconds.

List operation test

def test1():
   l = []
   for i in range(1000):
      l = l + [i]
def test2():
   l = []
   for i in range(1000):
      l.append(i)
def test3():
   l = [i for i in range(1000)]
def test4():
   l = list(range(1000))

from timeit import Timer

t1 = Timer("test1()", "from __main__ import test1")
print("concat ",t1.timeit(number=1000), "seconds")
t2 = Timer("test2()", "from __main__ import test2")
print("append ",t2.timeit(number=1000), "seconds")
t3 = Timer("test3()", "from __main__ import test3")
print("comprehension ",t3.timeit(number=1000), "seconds")
t4 = Timer("test4()", "from __main__ import test4")
print("list range ",t4.timeit(number=1000), "seconds")

# ('concat ', 1.7890608310699463, 'seconds')
# ('append ', 0.13796091079711914, 'seconds')
# ('comprehension ', 0.05671119689941406, 'seconds')
# ('list range ', 0.014147043228149414, 'seconds')

pop operation test

x = range(2000000)
pop_zero = Timer("x.pop(0)","from __main__ import x")
print("pop_zero ",pop_zero.timeit(number=1000), "seconds")
x = range(2000000)
pop_end = Timer("x.pop()","from __main__ import x")
print("pop_end ",pop_end.timeit(number=1000), "seconds")

# ('pop_zero ', 1.9101738929748535, 'seconds')
# ('pop_end ', 0.00023603439331054688, 'seconds')

Test the pop operation: As can be seen from the results, the efficiency of popping the last element is much higher than that of popping the first element

Can you try the append(value) and insert(0, value) of the list by yourself, that is, one insert after and one insert before? ? ?

Time complexity of list built-in operations

Time complexity of built-in operations on dict


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325703232&siteId=291194637