# python -m timeit '"-".join([str(n) for n in range(100) if n%2 == 0])' # 取模求偶数 20000 loops, best of 5: 12.5 usec per loop # python -m timeit '"-".join([str(n) for n in range(0,100,2)])' # 步进 50000 loops, best of 5: 8.85 usec per loop # python -m timeit '"-".join([str(n) for n in range(100) if n&1 == 0])' # 位运算判断奇偶 20000 loops, best of 5: 14.3 usec per loop
不科学1: 位运算竟然比取模慢?
如果不是一个字符串而是一个脚本:
def test_normal(): tmp = "" for x in range(100): if x % 2 == 0: if tmp: tmp = tmp+"-"+str(x) else: tmp = str(x) return tmp
if __name__ == '__main__': print(test_normal())
可以下面方式变通使用
# python -m base64 test_string_join.py | python -m base64 -d | python -m timeit 50000000 loops, best of 5: 5.33 nsec per loop
不科学2: 50000000循环只需要5.33纳秒,而之前的用例20000循环需要12.5微秒
标准库中还有 pdb && profile && pstats 使用比较复杂,暂时就不介绍
pypy3 -m timeit '[{} for n in range(1000)]' WARNING: timeit is a very unreliable tool. use pyperf or something elsefor real measurements pypy3 -m pip install pyperf pypy3 -m pyperf timeit '[{} for n in range(1000)]' ------------------------------------------------------------ 100000 loops, average of 7: 7.3 +- 0.107 usec per loop (using standard deviation)
[tywork@liujunhong_szfsfz_work1 config]$ pypy3 -m pyperf timeit '[{} for n in range(1000)]' ........ Mean +- std dev: 8.42 us +- 0.25 us [tywork@liujunhong_szfsfz_work1 config]$ [tywork@liujunhong_szfsfz_work1 config]$ [tywork@liujunhong_szfsfz_work1 config]$ [tywork@liujunhong_szfsfz_work1 config]$ pypy3 -m pyperf timeit '[dict() for n in range(1000)]' ......... Mean +- std dev: 29.6 us +- 1.1 us
13. pydoc
本地服务方式查看python代码文档
# python -m pydoc -p 8080 # 启动一个web服务 Server ready at http://localhost:8080/ Server commands: [b]rowser, [q]uit server> b
文档效果如图
14. test
执行python自带的测试用例,查看系统支持那些特性
# python -m test.regrtest -u cpu == CPython 2.7.16 (default, Jun 5 2020, 22:59:21) [GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- == Darwin-19.6.0-x86_64-i386-64bit little-endian
== /private/var/folders/mv/3vgd3mdx2453clfcst7qlm280000gn/T/test_python_13470 == CPU count: 12 Run tests sequentially 0:00:00 load avg: 2.53 [ 1/404] test_grammar ... = Tests result: FAILURE ==