[Python] timeit测试代码运行效率
2023-09-11 14:14:58 时间
python中有两种方法判断一个数是不是偶数或者奇数:
In [29]: 3&1 Out[29]: 1 In [30]: 3%2 Out[30]: 1 In [31]: 4&1 Out[31]: 0 In [32]: 4%2 Out[32]: 0
当不知道 采用 % 或 & 哪种 判断 奇偶的方法运行效率更高的时候
利用python timeit来测定
二进制与操作&1判断偶奇数:
def test1(x): for r in range(1,x): if r&1: pass
%2求余判断偶奇数:
def test2(x): for r in range(1,x): if r%2: pass
测试函数
def test1(x): for r in range(1,x): if r&1: pass %timeit test1(1000000) 60.6 ms ± 1.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
def test2(x): for r in range(1,x): if r%2: pass %timeit test2(1000000) 48.7 ms ± 766 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
结果显而易见
相关文章
- python 生成requirements.txt
- Python使用Thrift
- python: easyocr的安装和使用(easyocr 1.6.2 / Python 3.7.15 )
- Python:基本运算、基本函数(包括复数)、Math模块、NumPy模块
- 【Python实战】python中含有中文字符无法运行
- 笔记13:Python 和 Elasticsearch 构建简易搜索
- 【Python五篇慢慢弹(4)】模块异常谈python
- Python 爬取淘宝商品数据挖掘分析实战
- python-面向对象-11-异常
- [Python] Reuse Code in Multiple Projects with Python Modules
- [Python] Understand Mutable vs. Immutable objects in Python
- python的字符串内建函数
- python: easyocr的安装和使用(easyocr 1.6.2 / Python 3.7.15 )
- Python 办公自动化,全网最全整理来了!拒绝无效率加班!
- Python:利用python语言实现18位身份证号码和15位身份证号码相互转换
- Python语言学习:利用python语言实现调用内部命令(python调用Shell脚本)—命令提示符cmd的几种方法
- Python语言编程学习:利用python输出当前python版本、MSC版本型号
- Python:python语言中与时间有关的库函数简介、安装、使用方法(获取当前时间/计算程序块前后运行时间/模型训练时间或耗费时间)之详细攻略
- Python可视化数据分析01、python环境搭建
- 已解决2.Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and wi
- 〖Python自动化办公篇㉑〗- python实现邮件自动化 - 定时发送邮件
- Python搭建UDP网络通信模型,邀请ta来激情的聊天吧
- 【Python成长之路】Python爬虫 --requests库爬取网站乱码(xe4xb8xb0xe5xa)的解决方法
- 提高数据科学效率的 8 个Python神库
- 效率倍增,PyCaret:一个开源、低代码的 Python 机器学习工具
- 错误调试精确到行、match-case模式匹配... Python 3.10正式版真的很友好
- Python爬虫:tesseract识别图片验证码
- [python学习] 简单爬取图片站点图库中图片
- 用python来调用CAN通讯的DLL
- Python中docstring文档的写法
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
- 〖Python自动化办公篇⑲〗 - python实现邮件自动化 - 邮件发送
- 〖Python自动化办公篇⑳〗 - python实现邮件自动化 - 发送html邮件和带附件的邮件
- 〖Python自动化办公篇㉑〗- python实现邮件自动化 - 定时发送邮件
- 【Python实战】 ---- python 自带的 venv 虚拟环境更新 pip 失败