- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前有一个小型项目,我想在其中尽快对计算机上的20GB文件进行排序。想法是对文件进行分块,对块进行排序,合并块。我只是使用pyenv
为不同Python版本的radixsort代码计时,并且看到2.7.18
比3.6.10
,3.7.7
,3.8.3
和3.9.0a
快得多。在这个简单的示例中,有人可以解释为什么Python 3.x比2.7.18慢吗?是否添加了新功能?
import os
def chunk_data(filepath, prefixes):
"""
Pre-sort and chunk the content of filepath according to the prefixes.
Parameters
----------
filepath : str
Path to a text file which should get sorted. Each line contains
a string which has at least 2 characters and the first two
characters are guaranteed to be in prefixes
prefixes : List[str]
"""
prefix2file = {}
for prefix in prefixes:
chunk = os.path.abspath("radixsort_tmp/{:}.txt".format(prefix))
prefix2file[prefix] = open(chunk, "w")
# This is where most of the execution time is spent:
with open(filepath) as fp:
for line in fp:
prefix2file[line[:2]].write(line)
rb
/
wb
)打开文件,请参见“二进制模式”注释。在几次运行中,它们的速度要快一点。尽管如此,Python 2.7在所有运行中都更快。
import timeit
import numpy as np
durations = timeit.repeat(
'a["b"]',
repeat=10 ** 6,
number=1,
setup="a = {'b': 3, 'c': 4, 'd': 5}"
)
mul = 10 ** -7
print(
"mean = {:0.1f} * 10^-7, std={:0.1f} * 10^-7".format(
np.mean(durations) / mul,
np.std(durations) / mul
)
)
print("min = {:0.1f} * 10^-7".format(np.min(durations) / mul))
print("max = {:0.1f} * 10^-7".format(np.max(durations) / mul))
cp
:230s chunk_data
执行时间的差异也很大,但是Python 2.7的平均值明显低于Python3.x。因此,这似乎不是像我在这里尝试的那样简单的I/O方案。
import time
import sys
import os
version = sys.version_info
version = "{}.{}.{}".format(version.major, version.minor, version.micro)
if os.path.isfile("numbers-tmp.txt"):
os.remove("numers-tmp.txt")
t0 = time.time()
with open("numbers-large.txt") as fin, open("numers-tmp.txt", "w") as fout:
for line in fin:
fout.write(line)
t1 = time.time()
print("Python {}: {:0.0f}s".format(version, t1 - t0))
最佳答案
这是多种效果的组合,多数情况是Python 3在文本模式下工作时需要执行unicode解码/编码,而在二进制模式下,它将通过专用的缓冲IO实现发送数据。
首先,使用 time.time
来衡量执行时间会消耗时间,因此包括了各种与Python不相关的事情,例如OS级缓存和缓冲以及存储介质的缓冲。它还反射(reflect)了对需要存储介质的其他过程的任何干扰。这就是为什么您会在计时结果中看到这些疯狂的变化。这是我的系统的结果,每个版本连续运行七次:
py3 = [660.9, 659.9, 644.5, 639.5, 752.4, 648.7, 626.6] # 661.79 +/- 38.58
py2 = [635.3, 623.4, 612.4, 589.6, 633.1, 613.7, 603.4] # 615.84 +/- 15.09
>>> from scipy.stats import ttest_ind
>>> ttest_ind(p2, p3)[1]
0.018729004515179636
time.clock
完成,而Python 3.3+提供
time.process_time
。这两个功能报告以下时间:
py3_process_time = [224.4, 226.2, 224.0, 226.0, 226.2, 223.7, 223.8] # 224.90 +/- 1.09
py2_process_time = [171.0, 171.1, 171.2, 171.3, 170.9, 171.2, 171.4] # 171.16 +/- 0.16
550_000_000
),每次迭代总计约97.7纳秒。
In [1]: %timeit b'000000000000000000000000000000000000'.decode().encode()
162 ns ± 2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
"rb"
和
"wb"
而不是文本模式
"r"
和
"w"
。这样可以减少Python 3的计时结果,如下所示:
py3_binary_mode = [200.6, 203.0, 207.2] # 203.60 +/- 2.73
In [2]: class C:
...: def f(self): pass
...:
In [3]: x = C()
In [4]: %timeit x.f()
82.2 ns ± 0.882 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In [5]: %timeit x
17.8 ns ± 0.0564 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
%timeit x
度量了解析全局名称
x
的额外开销,因此属性查找和函数调用使
82.2 - 17.8 == 64.4
秒。从上面的往返数据中减去此开销两次,则为
162 - 2*64.4 == 33.2
秒。
io.BufferedWriter
的
.write
的(相当复杂的)实现,而在Python 2中
file.write
method进行得非常简单到
fwrite
。
$ python3.8
>>> type(open('/tmp/test', 'wb'))
<class '_io.BufferedWriter'>
$ python2.7
>>> type(open('/tmp/test', 'wb'))
<type 'file'>
py2_binary_mode = [212.9, 213.9, 214.3] # 213.70 +/- 0.59
dict
实现。为了衡量这种效果,我们可以创建一个相应的设置:
from __future__ import print_function
import timeit
N = 10**6
R = 7
results = timeit.repeat(
"d[b'10'].write",
setup="d = dict.fromkeys((str(i).encode() for i in range(10, 100)), open('test', 'rb'))", # requires file 'test' to exist
repeat=R, number=N
)
results = [x/N for x in results]
print(['{:.3e}'.format(x) for x in results])
print(sum(results) / R)
$ python3.8 -c "print(len({str(i).encode() for i in range(10, 100)}))"
90
$ python2.7 -c "print len({str(i).encode() for i in range(10, 100)})"
90
关于python - 自python 2.7以来,I/O变慢了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62079732/
我已经在谷歌上搜索这个问题一段时间了,但我还没有找到有效的解决方案。 问题是 SSH 登录到我的服务器突然变得很慢。我可以看到身份验证需要大约 10 秒才能继续,这是我的 ssh 详细日志: Open
我正在使用 AVPlayer 在我的项目中播放在线视频。视频播放良好。现在我想减少/增加视频的 fps。以下是我正在使用的代码: self.asset = [AVAsset assetWithURL:
在 Raspberry Pi 上运行两个使用 python gpio 引脚的程序时,一个变慢。一种是磁传感器,另一种是温湿度传感器。后者是放慢速度的。它不是每 2 秒打印一次温度,而是每 5 到 10
我从 Redis 向我的应用程序提供一个 json,然后我对其进行解码和循环。 这是我从 Redis 提供的 json 的样子: [ { "titel": "test 1",
Ejabberd 版本:19.9.0 在发送 OMEMO 消息时(使用 websockets),例如
我们有相当大的代码库(150 多个项目、400000 多行 Java 代码、一些 Groovy 和 Gradle 代码、一些 Perl 代码、一些 XML、大量 JSP 等)。我设法在 Spring
我在一个网站上工作,您可以在其中创建 svg 艺术品,这意味着您可以动态添加元素、缩放、颜色并移动它们。 问题是,当你开始在他们身上施加阴影时,一切都会开始变慢。对于这个的现场演示,this是我正在开
有没有办法分析 Vim 插件? 当我打开一个大的 .py 时,我的 MacVim 变得越来越慢。我知道我可以取消选择所有插件并逐一重新选择以检查哪个插件是罪魁祸首,但是有没有更快的方法? 我的 dot
我正在构建一个JavaFX应用程序。我知道它使用反射,并且反射可能不如我在代码中构建 UI 时那么快。 所以, 如何设计我的 Controller 以使由反射引起的开销尽可能小? 带/不带 @FXML
我对 UITableViewCell 进行了子类化显示从 1 到 70 的数字。 在每个单元格中,我都在检查中奖号码并检查他们的背景。问题是,经过几次滚动后,tableview 变得非常缓慢,甚至无法
如果我想group_by 和filter 那些在数据集中有任何NA 或factor 值的,我想在 dplyr 中使用 any 函数,但发现它对 NAs 或 factor 运行缓慢(但不是为了寻找任何数
我有一个问题。在我的解决方案中,我需要将数千个数据插入数据库。我正在使用批处理准备语句在一个请求中插入多行。在我调用插入几次之后, hibernate 变得更慢了。 我猜它会在我提交后检查数据库是否有
我从 json url 获取数据,但是当我想加载图像时,速度非常慢! class NewsTableViewController: UITableViewController { var id
我有一个相当简单的托管 Realm 对象 RealmAlertItem由一些字符串和 float 组成。我有一个函数 showAlertNotification()随后被调用(从网络外部触发)并且它依
请参阅下面的表格结构。 CREATE TABLE `oarc` ( `ID` bigint(20) NOT NULL AUTO_INCREMENT, `zID` int(11) NOT N
IntelliJ 慢得像爬行。键之间没有 1-2 个延迟几乎无法打字。我已经更新了堆大小。我在我的 Macbook Pro 上运行大约 2GB RAM。自从它一直在放缓。我已经增加了堆大小,但无济于事
我的 Web 应用程序遇到了性能问题。发现瓶颈是db。应用程序在具有 4 个 CPU 和 2GB RAM 的 LAMP 服务器 (VPS) 上运行。 将新记录插入数据库(包含大约 100.000 条记
我有关于自定义 DispatchQueue 的问题。 我创建了一个队列,并将其用作captureOutput:方法的队列。这是一个代码片段: //At the file header private
我是一名移动 QA。现在我们有一个关于网络响应和 UI 渲染之间的竞争条件的问题。我们猜测如果 UI 渲染比网络响应慢,那么它就会崩溃。 我们已经尝试通过使用 Charles 的本地 map 功能来加
我在 firefox 中遇到了一些奇怪的行为,我正在构建一个单页作品集,作为一名平面设计师,编码一直很困难。我想平滑地控制导航,然后向所有元素添加缩放(最初设计为 1920x1080 全屏)。讲师扔了
我是一名优秀的程序员,十分优秀!