new_benchmark.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # New benchmark that only compares different methods in function of the state complexity
  2. # This benchmark works out of the context of a real simulation!
  3. # Complexity is defined as the number of attributes
  4. from copy import deepcopy
  5. import cPickle as pickle
  6. import time
  7. import random
  8. class AttributesState(object):
  9. def __init__(self, complexity):
  10. self.complexity = complexity
  11. for f in xrange(complexity):
  12. setattr(self, str(f), None)
  13. def set_initial(self):
  14. for f in xrange(complexity):
  15. setattr(self, str(f), random.random())
  16. def copy(self):
  17. a = AttributesState(self.complexity)
  18. for f in xrange(self.complexity):
  19. setattr(a, str(f), getattr(self, str(f)))
  20. return a
  21. class SizeState(object):
  22. def __init__(self, complexity):
  23. self.values = [None] * complexity
  24. self.complexity = complexity
  25. def set_initial(self):
  26. self.values = [random.random() for _ in xrange(complexity)]
  27. def copy(self):
  28. a = SizeState(self.complexity)
  29. a.values = list(self.values)
  30. return a
  31. def benchmark(s, f, out):
  32. samples = 1000
  33. for c in range(0, 300, 5):
  34. if s == "AttributesState":
  35. state = AttributesState(c)
  36. elif s == "SizeState":
  37. state = SizeState(c)
  38. start = time.time()
  39. for _ in xrange(samples):
  40. f(state)
  41. t = (time.time() - start) / samples * 1000
  42. print("%i %f" % (c, t))
  43. out.write("%i %f\n" % (c, t))
  44. for s in ["AttributesState", "SizeState"]:
  45. for f in [("deepcopy", lambda i: deepcopy(i)), ("pickle", lambda i: pickle.loads(pickle.dumps(i))), ("custom", lambda i: i.copy())]:
  46. print("%s -- %s" % (s, f[0]))
  47. out = open("%s_%s" % (s, f[0]), 'w')
  48. benchmark(s, f[1], out)
  49. out.close()