前面几篇文章总结了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 效率比较的更多相关文章

  1. Python 中,字符串"连接"效率最高的方式是?一定出乎你的意料

    网上很多文章人云亦云,字符串连接应该使用「join」方法而不要用「+」操作.说前者效率更高,它以更少的代价创建新字符串,如果用「+」连接多个字符串,每连接一次,就要为字符串分配一次内存,效率显得有点低 ...

  2. Python中的bool类型

    Python 布尔类型 bool python 中布尔值使用常量True 和 False来表示:注意大小写 比较运算符< > == 等返回的类型就是bool类型:布尔类型通常在 if 和 ...

  3. python中in在list和dict中查找效率比较

    转载自:http://blog.csdn.net/wzgbm/article/details/54691615 首先给一个简单的例子,测测list和dict查找的时间: ,-,-,-,-,,,,,,] ...

  4. python中列表的insert和append的效率对比

    python中insert和append方法都可以向列表中插入数据只不过append默认插入列表的末尾,insert可以指定位置插入元素. 我们来测试一下他俩插入数据的效率: 测试同时对一个列表进行插 ...

  5. 用 ElementTree 在 Python 中解析 XML

    用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...

  6. python中的反射

    在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...

  7. python中协程

    在引出协成概念之前先说说python的进程和线程. 进程: 进程是正在执行程序实例.执行程序的过程中,内核会讲程序代码载入虚拟内存,为程序变量分配空间,建立 bookkeeping 数据结构,来记录与 ...

  8. 详解Python中的循环语句的用法

    一.简介 Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性.须重要理解,if.while.for以及与它们相搭配的 else. elif.break.continue和pass语句 ...

  9. Python 中的数据结构总结(一)

    Python 中的数据结构 “数据结构”这个词大家肯定都不陌生,高级程序语言有两个核心,一个是算法,另一个就是数据结构.不管是c语言系列中的数组.链表.树和图,还是java中的各种map,随便抽出一个 ...

随机推荐

  1. 个人项目-WC(Java实现)

    一.Github项目地址: https://github.com/kestrelcjx/-WC-Java- 二.PSP表格 PSP2.1 Personal Software Process Stage ...

  2. 04——Solr学习之项目中使用solr

    借鉴博客:https://blog.csdn.net/kisscatforever/article/details/76744768 完全可以跟着他这个来,清晰明了. 一.来说说怎么使用solr这玩意 ...

  3. (原)堆叠hourglass网络

    转载请注明出处: https://www.cnblogs.com/darkknightzh/p/11486185.html 论文: https://arxiv.org/abs/1603.06937 官 ...

  4. 十九、Python之socket编程

    socket(套接字)就是建立连接,发送,接收.大部分网络协议都是建立在socket之上的,例如:http,ftp,smtp等等     socket用于描述IP地址和端口,是一个通信链的句柄.应用程 ...

  5. 【目录】Jmeter系列

    为天地立心,为生民立命.为往圣继绝学,为万世开太平. ---<横渠四句>·张载 Jmeter(一)简介以及环境搭建 Jmeter(二)Jmeter目录介绍 Jmeter(三)Test-Pl ...

  6. <人人都懂设计模式>-装饰模式

    书上,真的用一个人穿衣打拌来讲解装饰模式的呢. from abc import ABCMeta, abstractmethod class Person(metaclass=ABCMeta): def ...

  7. 遇到libgflags.a(gflags.cc.o): relocation R_X86_64_32 against `.rodata.str1.1' ca时

    glfag编译成动态库gflags 正确的安装方法是这样的: Need cmake >2.8.4 (current is 2.8.3) mkdir build cd build cmake -D ...

  8. IDEA中常用的一些设置

    一.idea常用设置1.报错级别    idea默认不会像eclipse一样需要ctrl+s进行保存,并且在保存时会进行编译(可以在File>Settings>Build,Executio ...

  9. 从架构开始谈dubbo(一)

    架构发展史 一.单体应用架构      当网站流量很小时,所有的功能写在一个项目中,打包部署在tomcat中.          例如:公司管理系统,超市的收银系统         也可以将单体应用部 ...

  10. 15-cmake语法-math

    math 数学表达式 math(EXPR <output variable> <math expression>) 例子: math(EXPR VAR "${VAR} ...