fork download
  1. import time
  2. import queue
  3. import threading
  4. from fractions import gcd
  5.  
  6.  
  7. THREADS = 2
  8.  
  9.  
  10. def create_set_with_thread(t):
  11. init = time.time()
  12. set_ = list()
  13. q = queue.Queue()
  14.  
  15. def _f():
  16. while True:
  17. x = q.get()
  18. if gcd(x, t) == 1:
  19. set_.append(x)
  20. try:
  21. q.task_done()
  22. except ValueError:
  23. break
  24.  
  25. for x in range(1, t):
  26. q.put(x)
  27.  
  28. for num in range(THREADS):
  29. thread = threading.Thread(target=_f)
  30. thread.daemon = True
  31. thread.start()
  32. q.join()
  33.  
  34. print('threaded set created in', get_passed_time(init))
  35. return set_
  36.  
  37.  
  38. def create_set(t):
  39. init = time.time()
  40. out = []
  41. for x in range(1, t):
  42. if gcd(x, t) == 1:
  43. out.append(x)
  44. print('set created in', get_passed_time(init))
  45. return out
  46.  
  47.  
  48. def get_passed_time(cur_time):
  49. cur_time = time.time() - cur_time
  50. if cur_time > 60:
  51. cur_time /= 60
  52. label = 'mins'
  53. else:
  54. label = 'seconds'
  55. return '%.5s %s' % (cur_time, label)
  56.  
  57.  
  58. t = 10 ** 5
  59. t0 = create_set_with_thread(t)
  60. t1 = create_set(t)
  61. print(len(t0), len(t1))
  62.  
Success #stdin #stdout 1.75s 30992KB
stdin
Standard input is empty
stdout
threaded set created in 1.445 seconds
set created in 0.253 seconds
40000 40000