Created
January 5, 2020 12:54
-
-
Save viktorasm/7ea124dc2e666223369e09508c3e4a40 to your computer and use it in GitHub Desktop.
Python equality test for old vs new objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cProfile | |
import pstats | |
from random import random | |
class SampleObject: | |
def __init__(self): | |
self.sample_data = random() | |
class SampleObjectNew(object): | |
def __init__(self): | |
self.sample_data = random() | |
old_objects = [SampleObject() for _ in xrange(3000)] | |
new_objects = [SampleObjectNew() for _ in xrange(len(old_objects))] | |
def compare_with_id(l): | |
for a in l: | |
for b in l: | |
equal = id(a)==id(b) | |
def compare_with_equality(l): | |
for a in l: | |
for b in l: | |
equal = a==b | |
for sample_list in (old_objects, new_objects): | |
print "Testing performance for type", sample_list[0].__class__.__name__ | |
p = cProfile.Profile() | |
p.enable() | |
compare_with_id(sample_list) | |
compare_with_equality(sample_list) | |
p.disable() | |
sortby = 'cumulative' | |
ps = pstats.Stats(p).sort_stats(sortby) | |
ps.print_stats() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Testing performance for type SampleObject | |
18000003 function calls in 17.105 seconds | |
Ordered by: cumulative time | |
ncalls tottime percall cumtime percall filename:lineno(function) | |
1 14.528 14.528 14.528 14.528 benchmark.py:25(compare_with_equality) | |
1 1.890 1.890 2.576 2.576 benchmark:20(compare_with_id) | |
18000000 0.687 0.000 0.687 0.000 {id} | |
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} | |
Testing performance for type SampleObjectNew | |
18000003 function calls in 2.984 seconds | |
Ordered by: cumulative time | |
ncalls tottime percall cumtime percall filename:lineno(function) | |
1 1.884 1.884 2.567 2.567 benchmark.py:20(compare_with_id) | |
18000000 0.683 0.000 0.683 0.000 {id} | |
1 0.417 0.417 0.417 0.417 benchmark.py:25(compare_with_equality) | |
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment