stress_heap.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # stress test for the heap by allocating lots of objects within threads
  2. # allocates about 5mb on the heap
  3. #
  4. # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd
  5. try:
  6. import utime as time
  7. except ImportError:
  8. import time
  9. import _thread
  10. def last(l):
  11. return l[-1]
  12. def thread_entry(n):
  13. # allocate a bytearray and fill it
  14. data = bytearray(i for i in range(256))
  15. # run a loop which allocates a small list and uses it each iteration
  16. lst = 8 * [0]
  17. sum = 0
  18. for i in range(n):
  19. sum += last(lst)
  20. lst = [0, 0, 0, 0, 0, 0, 0, i + 1]
  21. # check that the bytearray still has the right data
  22. for i, b in enumerate(data):
  23. assert i == b
  24. # print the result of the loop and indicate we are finished
  25. with lock:
  26. print(sum, lst[-1])
  27. global n_finished
  28. n_finished += 1
  29. lock = _thread.allocate_lock()
  30. n_thread = 10
  31. n_finished = 0
  32. # spawn threads
  33. for i in range(n_thread):
  34. _thread.start_new_thread(thread_entry, (10000,))
  35. # wait for threads to finish
  36. while n_finished < n_thread:
  37. time.sleep(1)