fork download
  1. from timeit import default_timer as timer
  2. from threading import Thread
  3. ####from multiprocessing import Process as Thread
  4. import os
  5.  
  6. # for ideone.com
  7. class NullFile:
  8. def write(self, data):
  9. pass
  10. devnull = NullFile()
  11. #
  12.  
  13. def printNumbers(lowEnd, highEnd):
  14. while(lowEnd <= highEnd):
  15. print(repr(lowEnd),file=devnull)
  16. lowEnd += 1
  17.  
  18.  
  19. countTo = 100000
  20.  
  21. #Test using 1 thread.
  22. startSingleThread = timer()
  23. printNumbers(0,countTo)
  24. elapsedSingleThread = (timer() - startSingleThread)
  25.  
  26. #Test using 10 threads
  27. numberOfThreads = 10
  28. countAmountPerThread = countTo//numberOfThreads
  29.  
  30. startTenThread = timer()
  31. threads = []
  32. for i in range(numberOfThreads):
  33. threadLowEnd = i*countAmountPerThread
  34. threadHighEnd = (i+1)*countAmountPerThread
  35. t = Thread(target=printNumbers, args=(threadLowEnd,threadHighEnd,))
  36. threads.append(t)
  37. t.daemon = True
  38. t.start()
  39.  
  40. #Join all existing threads to main thread.
  41. for t in threads: t.join()
  42.  
  43. elapsedTenThread = (timer() - startTenThread)
  44.  
  45. print("Time for 1 thread: " + repr(elapsedSingleThread))
  46. print("time for 10 threads: " + repr(elapsedTenThread))
  47.  
Success #stdin #stdout 0.78s 14536KB
stdin
Standard input is empty
stdout
Time for 1 thread: 0.3638269901275635
time for 10 threads: 0.369966983795166