python 3 中最快的标准输入/输出 IO? [英] Fastest stdin/out IO in python 3?

查看:33
本文介绍了python 3 中最快的标准输入/输出 IO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 python 3.1.2 解决 SPOJ.pl 上的一些问题,有些人在简单问题上的快速结果让我想知道是否有更快的方法来处理输入和输出.

I've been solving a few problems on SPOJ.pl using python 3.1.2 and some peoples fast result on simple problems makes me wonder if there is a faster way to handle input and output.

我试过使用

input()
print()

sys.stdin.readline()
sys.stdout.write()

或者更确切地说

for line in sys.stdin:
    #Handle input
    sys.stdout.write(output)

处理每一行.我还尝试收集列表中的所有输出,并在处理完所有内容后立即打印出来.

to process each line. I've also tried to collect all output in lists and print all at once when everything is processed.

但所有这些都会产生相似的执行时间.

But all of these produce similar execution times.

有没有更快的方法来处理来自 stdin/out 的输入和输出?

Is there any faster way to handle input and output from stdin/out?

推荐答案

以下可能是最快的:

  1. 使用 os.read(0, some_big_enough_number) 一次性读取所有输入.

  1. Read all the input at once using os.read(0, some_big_enough_number).

处理输出,将结果收集在列表results中.

Process the output, collecting the results in a list results.

使用os.write(1, "".join(results))一次性写入所有输出.

Write all the output at once using os.write(1, "".join(results)).

我记得有一个案例,我注意到 os.read()os.write() 有时比使用 Python I/O 更快,但我没有不记得细节.

I remember one case where I noticed that os.read() and os.write() are sometimes faster than using Python I/O, but I don't remember the details.

这篇关于python 3 中最快的标准输入/输出 IO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆