Python的os.path.join很慢吗? [英] Is Python's os.path.join slow?

查看:117
本文介绍了Python的os.path.join很慢吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我os.path.join在python中非常慢,我应该改用字符串连接('%s/%s' % (x, y)).真的有那么大的区别吗?如果可以的话,我该如何追踪呢?

I've been told os.path.join is horribly slow in python and I should use string concatenation ('%s/%s' % (x, y)) instead. Is there really that big a difference and if so how can I track it?

推荐答案

$ python -mtimeit -s 'import os.path' 'os.path.join("/root", "file")'
1000000 loops, best of 3: 1.02 usec per loop
$ python -mtimeit '"/root" + "file"'
10000000 loops, best of 3: 0.0223 usec per loop

是的,它慢了将近50倍. 1微秒仍然是什么,所以我真的不会考虑其中的差异.使用os.path.join:它是跨平台的,更具可读性,并且不易出错.

So yes, it's nearly 50 times slower. 1 microsecond is still nothing though, so I really wouldn't factor the difference in. Use os.path.join: it's cross-platform, more readable and less bug-prone.

现在有两个人评论说import解释了差异.这是不正确的,因为-s是设置标志,因此import并未计入报告的运行时中.阅读文档.

Two people have now commented that the import explains the difference. This is not true, as -s is a setup flag thus the import is not factored into the reported runtime. Read the docs.

这篇关于Python的os.path.join很慢吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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