Python字典查找性能

Python字典查找性能

 

timeit.repeat

timeit.repeat默认会执行3轮,每轮执行1000000次。返回每轮的总执行时间列表

 

字典获取性能

大家都知道字典获取分为

中括号获取,获取不到会抛出KeyError

get获取,获取不到会返回默认值

下面比较两种获取方式的性能

数据准备

一条简单一条复杂

# logging标准库的level字典
level_mapping = {"CRITICAL": 50, "FATAL": 50, "ERROR": 40, "WARN": 30, "WARNING": 30, "INFO": 20, "DEBUG": 10, "NOTSET": 0}
# elasticsearch日志
record = {"_index": "logstash-project.test-env.release-user.root-2021", "_type": "doc", "_id": "2f60jn0BaH-cdSPUSkiF", "_version": 1, "_score": None, "_source": {"method": "GET", "index_name": "project.test-env.release-user.root", "@version": "flask", "path": "D:\alpha\flask\logstash\core\flask.py", "logger_name": "flask.exception", "stack_info": None, "user": "root", "@timestamp": "2021-12-06T07:45:20.056Z", "level": "ERROR", "thread_name": "Thread-5", "type": "exception", "env": "release", "process": 8716, "funcName": "exceptions", "port": 55792, "project": "test", "tags": [], "lineno": 89, "request": {"headers": {"Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", "Postman-Token": "359faa6e-9527-4de7-82ff-eecb92656875", "User-Agent": "PostmanRuntime/7.28.4", "Cookie": "csrftoken=bf58fmaG5wBVabJwBeD8srVsfw7EjKe0VN7xD8mu817UzVm", "Accept": "*/*", "Host": "127.0.0.1:5000"}, "args": {"a": "11", "b": "22"}}, "message": "division by zero", "host": "DESKTOP-JCQ9527", "status_code": 500, "stack_trace": "Traceback (most recent call last):
  File "D:\Envs\logstash\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Envs\logstash\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\flask\logstash\app.py", line 112, in get_raise
    a/0
ZeroDivisionError: division by zero
", "remote_addr": "127.0.0.1", "url": "http://127.0.0.1:5000/raise?a=11&b=22"}, "fields": {"@timestamp": ["2021-12-06T07:45:20.056Z"]}, "sort": [1638776720056]}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Python字典查找性能