python中 jsonchema 与 shema 效率比较
前面几篇文章总结了python中jsonschema与schema的用法,这里测试一下两者的效率:
上代码:
import time
from jsonschema import validate, draft7_format_checker
from jsonschema.exceptions import SchemaError, ValidationError
from schema import Schema, And, Optional, SchemaError, Regex
def tags_check(tags_list):
if len(tags_list) < 1 or len(tags_list) > 5:
return False
for tag in tags_list:
if len(tag) < 2:
return False
return True
def id_generator(start=1):
while 1:
yield start
start += 1
class DataFactory(object):
def __init__(self):
self.id_g = id_generator()
def create_data(self):
idn = next(self.id_g)
price = 5.5 + idn
json_data = {
"id": idn,
"name": "jarvis手册%d" % idn,
"info": "贾维斯平台使用手册%d" % idn,
"price": price,
"tags": ["jar"],
"date": "2019-5-25",
"others": {
"info1": "1111",
"info2": "2222"
}
}
return json_data
schema1 = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "book info",
"description": "some information about book",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a book",
"type": "integer",
"minimum": 1
},
"name": {
"description": "book name",
"type": "string",
"minLength": 3,
"maxLength": 30
},
"info": {
"description": "simple information about book",
"type": "string",
"minLength": 10,
"maxLength": 60
},
"price": {
"description": "book price",
"type": "number",
"multipleOf": 0.5,
"minimum": 5.0,
"maximum": 111111.0,
},
"tags": {
"type": "array",
"additonalItems": {
"type": "string",
"miniLength": 2
},
"miniItems": 1,
"maxItems": 5,
},
"date": {
"description": "书籍出版日期",
"type": "string",
"format": "date",
},
"bookcoding": {
"description": "书籍编码",
"type": "string",
"pattern": "^[A-Z]+[a-zA-Z0-9]{12}$"
},
"others": {
"description": "其他信息",
"type": "object",
"properties": {
"info1": {
"type": "string"
},
"info2": {
"type": "string"
}
}
}
},
"required": [
"id", "name", "info", "price", "tags"
]
}
schema2 = {
"id": And(int, lambda x: 1 <= x, error="id必须是整数,大于等于100"),
"name": And(str, lambda s: 3 <= len(s) <= 30, error="name长度3-10"),
"info": And(str, lambda s: 10 <= len(s) <= 60, error="info信息出错"),
"price": And(float, lambda x: (5.0 < x < 111111.0) and (x % 0.5 == 0), error="price必须是大于5.0小于111.0的小数,且能被0.5整除"),
"tags": And(list, tags_check, error="tags出错"),
Optional("date"): And(str, error="日期格式出错"),
Optional("bookcoding"): And(str, Regex("^[A-Z]+[a-zA-Z0-9]{12}$"), error="书籍编码出错"),
Optional("others"): {
"info1": str,
"info2": str
},
}
def time_jsonschema(data):
start_time = time.time()
for json_data in data:
try:
validate(instance=json_data, schema=schema1, format_checker=draft7_format_checker)
except SchemaError as e:
print("验证模式出错:{}\n提示信息:{}".format(" --> ".join([i for i in e.path]), e.message))
except ValidationError as e:
print("出错字段:{}\n提示信息:{}".format(" --> ".join([i for i in e.path]), e.message))
else:
continue
end_time = time.time()
return end_time - start_time
def time_schema(data):
start_time = time.time()
for json_data in data:
try:
Schema(schema2).validate(json_data)
except SchemaError as e:
print(e)
else:
continue
end_time = time.time()
return end_time - start_time
if __name__ == "__main__":
data = DataFactory()
data_list = [data.create_data() for i in range(10000)]
t1 = time_jsonschema(data_list)
t2 = time_schema(data_list)
print("jsonschema:schema = {}:{} = {}:1\n".format(t1, t2, t1/t2))
结果分析:
# 10条数据时:
jsonschema:schema = 0.012000083923339844:0.0019941329956054688 = 5.517694882831181:1
# 100条数据时:
jsonschema:schema = 0.10173273086547852:0.023936033248901367 = 4.180191742616664:1
# 1000条数据时:
jsonschema:schema = 0.9435069561004639:0.2263953685760498 = 4.127518805860752:1
# 10000条数据时:
jsonschema:schema = 9.319035053253174:2.2689626216888428 = 4.1371787451116295:1
数据在10条的时候,多次测验,最终结果不稳定,耗时比在6.0 ,5.5,3.6左右,波动较大。
数据在100条的时候,多次测验,最终结果比较稳定,耗时比在3.85—4.3之间
数据在1000条的时候,多次测验,最终结果的耗时比在4.0—4.2之间
数据在10000条的时候,由于每次测试时间都比较长,故测试数据相对比较少,但耗时比在4.1左右
试验次数不是很多,基于上面代码和测试数据,schema 效率比 jsonschema 大约高出 4倍
python中 jsonchema 与 shema 效率比较的更多相关文章
- Python 中,字符串"连接"效率最高的方式是?一定出乎你的意料
网上很多文章人云亦云,字符串连接应该使用「join」方法而不要用「+」操作.说前者效率更高,它以更少的代价创建新字符串,如果用「+」连接多个字符串,每连接一次,就要为字符串分配一次内存,效率显得有点低 ...
- Python中的bool类型
Python 布尔类型 bool python 中布尔值使用常量True 和 False来表示:注意大小写 比较运算符< > == 等返回的类型就是bool类型:布尔类型通常在 if 和 ...
- python中in在list和dict中查找效率比较
转载自:http://blog.csdn.net/wzgbm/article/details/54691615 首先给一个简单的例子,测测list和dict查找的时间: ,-,-,-,-,,,,,,] ...
- python中列表的insert和append的效率对比
python中insert和append方法都可以向列表中插入数据只不过append默认插入列表的末尾,insert可以指定位置插入元素. 我们来测试一下他俩插入数据的效率: 测试同时对一个列表进行插 ...
- 用 ElementTree 在 Python 中解析 XML
用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...
- python中的反射
在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...
- python中协程
在引出协成概念之前先说说python的进程和线程. 进程: 进程是正在执行程序实例.执行程序的过程中,内核会讲程序代码载入虚拟内存,为程序变量分配空间,建立 bookkeeping 数据结构,来记录与 ...
- 详解Python中的循环语句的用法
一.简介 Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性.须重要理解,if.while.for以及与它们相搭配的 else. elif.break.continue和pass语句 ...
- Python 中的数据结构总结(一)
Python 中的数据结构 “数据结构”这个词大家肯定都不陌生,高级程序语言有两个核心,一个是算法,另一个就是数据结构.不管是c语言系列中的数组.链表.树和图,还是java中的各种map,随便抽出一个 ...
随机推荐
- python中for循环里去修改列表注意的事项
你的微信好友当中有 5 个推销的,他们存在一个列表 # black_list=['卖茶叶', '卖面膜', '卖保险', '卖花生', '卖手机'] # 当中, 请把这 5 个人分别从 black_l ...
- 数据库系统(四)---关系型数据库设计及E-R图
1.关系型数据库: 关系型数据库是一类采用关系模型作为逻辑数据模型的数据库系统,遵从数据库设计的基本步骤,包括:需求分析.概念结构设计.逻辑结构设计.物理结构设计.数据库实施.数据库的运行和维护等阶段 ...
- django framework插件类视图分页
分页 继承APIView类的视图中添加分页 from rest_framework.pagination import PageNumberPagination class MyPageNumberP ...
- nginx 的 重定向
1. ngx.redirect(uri, status?) 301/302重定向 redirect 为外部重定向,有两种形式: rewrite ^ /foo? redirect; # ngi ...
- 【JavaScript】案例一:使用JS完成注册页面表单校验——事件(onsubmit&onfocus&onblur)
(一)初版:事件(onsubmit) 步骤分析: 第一步:确定事件(onsubmit)并为其绑定一个函数 第二步:书写这个函数(获取用户输入的数据<获取数据时需要在指定位置定义一个 id> ...
- Detectron2源码阅读笔记-(三)Dataset pipeline
构建data_loader原理步骤 # engine/default.py from detectron2.data import ( MetadataCatalog, build_detection ...
- destoon中get_maincat函数的用法
求解get_maincat函数的用法,如get_maincat(0, $CATEGORY, 1),其中第一.二.三个参数分别表示什么,有谁知道,请介绍下,谢谢! 答:get_maincat() 三个参 ...
- Feign 报错:No fallback instance of type class xxx found for feign client xxx
通常需要确认配置内容: 开启 Hystrix:feign.hystrix.enabled=true Fallback类需要注解@Component 出处:https://www.jianshu.com ...
- opencart忘记登录密码怎么办
今天一位客户问opencart忘记登录密码怎么办,他们公司内部有几位员工同时在管理,可能是哪位同事把密码给改了没有跟大家说,现在都登录不了.这个只能数据库修改了.进入opencart的数据库,找到oc ...
- Kdevelop的C++断点调试设置
1. CMakeLists.txt 需要设置为 Debug 模式 示例 cmake_minimum_required(VERSION 2.8) Project (Eigen_test) include ...