SHARE
TWEET

Python - speed of print, sys.stdout.write and file.write

furas Jun 16th, 2018 (edited) 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import time
  2. import sys
  3.  
  4. text = '.'
  5. start = time.time()
  6. for _ in range(1_000_000):
  7.     print(text)
  8. end = time.time()
  9. result1 = end - start
  10.  
  11. text = 'hello world of long looooong strings to display'
  12. start = time.time()
  13. for _ in range(1_000_000):
  14.     print(text)
  15. end = time.time()
  16. result2 = end - start
  17.  
  18. text = 'hello world of long looooong strings to display'
  19. start = time.time()
  20. for _ in range(1_000_000):
  21.     sys.stdout.write(text + '\n')
  22. end = time.time()
  23. result3 = end - start
  24.  
  25. text = 'hello world of long looooong strings to display'
  26. f = open('temp.txt', 'w')
  27. start = time.time()
  28. for _ in range(1_000_000):
  29.     f.write(text + '\n')
  30. end = time.time()
  31. f.close()
  32. result4 = end - start
  33.  
  34. print(result1) # 10-11 seconds
  35. print(result2) # 24-25 seconds
  36. print(result3) # 19-20 seconds
  37. print(result4) # 0.9 seconds
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top