我编写了以下脚本来测试 Python 排序功能的速度:
from sys import stdin, stdout
lines = list(stdin)
lines.sort()
stdout.writelines(lines)
Run Code Online (Sandbox Code Playgroud)
然后,我将其与sort包含 1000 万行的文件上的 coreutils命令进行了比较:
$ time python sort.py <numbers.txt >s1.txt
real 0m16.707s
user 0m16.288s
sys 0m0.420s
$ time sort <numbers.txt >s2.txt
real 0m45.141s
user 2m28.304s
sys 0m0.380s
Run Code Online (Sandbox Code Playgroud)
内置命令使用了所有四个 CPU(Python 只使用了一个),但运行时间大约是其 3 倍!是什么赋予了?
我使用的是 Ubuntu 12.04.5(32 位)、Python 2.7.3 和sort8.13