Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from copy import copy, deepcopy
import pickle
import timeit
pickle_copy = lambda l: pickle.loads(pickle.dumps(l, -1))
case = 5
if case == 1:
## case 1: integer list
data = list(range(100000))
elif case == 2:
## case 2: empty class
class A:
pass
data = [A() for _ in range(100000)]
elif case == 3:
## case 3: class with two param
class B:
def __init__(self, n, m):
self.n = n
self.m = m
data = [B(i, i+1) for i in range(100000)]
elif case == 4:
## case 4: class
class C:
def __init__(self):
self.x = list(range(3))
self.y = list(range(3))
self.z = list(range(4))
data = [C() for i in range(100000)]
elif case == 5:
class D:
def __init__(self):
for i in range(10000):
exec('self.x{} = list(range(5))'.format(i))
data = D()
else:
raise NotImplementedError
NUM=10
copy_time = timeit.timeit('copy(data)', globals=globals(), number=NUM)
deepcopy_time = timeit.timeit('deepcopy(data)', globals=globals(), number=NUM)
pickle_time = timeit.timeit('pickle_copy(data)', globals=globals(), number=NUM)
print("copy_time: {:.2f}ms".format(copy_time * 1000 / NUM))
print("deepcopy_time: {:.2f}ms".format(deepcopy_time * 1000 / NUM))
print("pickle_time: {:.2f}ms".format(pickle_time * 1000 / NUM))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment