Advertisement
furas

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

Jun 16th, 2018
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement