为什么python打印功能更快但平滑较低?

发布于 2025-02-11 05:31:46 字数 810 浏览 0 评论 0原文

假设我有一些简单的代码,例如:

import time

tic = time.perf_counter()

for x in range(1000):
    print(str(x))

toc = time.perf_counter()
print(toc - tic)

它打印1000件事,然后打印出完成的时间。当我运行此功能时,我会得到:

0
1
2
3
4
5
6

… skipped for brevity …

995
996
997
998
999
2.0521691879999997

稍两秒钟。不错。

现在说我只想一次显示一个数字。我可以做:

import time

tic = time.perf_counter()

for x in range(1000):
    print('\r' + str(x), end = '')

toc = time.perf_counter()
print()
print(toc - tic)

我得到(最后)

999
0.46631713999999996

这似乎很奇怪,因为在第二个脚本中,您要打印更多的内容(一些\ r和x),而不是第一个脚本(Just x)。那么为什么会更快呢?

但是在第二个脚本中,输出非常平滑。看来该程序在110年代计数。为什么不像第一个一样迅速吐出数字?

顺便说一句,显然Sys.stdout.write()比print()快,而对于前者,第一个脚本和第二个脚本都是相同的速度,但是第二个脚本仍然不流畅。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文