Say I have some simple code such as the following:
import time
tic = time.perf_counter()
for x in range(1000):
print(str(x))
toc = time.perf_counter()
print(toc - tic)
It prints 1000 things, and then prints the time it took to do it. When I run this, I get:
0
1
2
3
4
5
6
… skipped for brevity …
995
996
997
998
999
2.0521691879999997
A little more than two seconds. Not bad.
Now say I wanted to only have a single number showing at a time. I could do :
import time
tic = time.perf_counter()
for x in range(1000):
print('\r' + str(x), end = '')
toc = time.perf_counter()
print()
print(toc - tic)
I get (at the very end)
999
0.46631713999999996
This seems weird, because in the second script, you’re printing more things (some \r’s and x) than the first script (just x). So why would it be faster?
But in the second script, the output is very un-smooth. It looks like the program is counting by 110s. Why doesn’t it just start spitting out numbers rapidly like in the first one?
By the way, apparently sys.stdout.write() is faster than print(), and with the former, both the first script and the second script are about the same speed, but the second script is still not smooth.