-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbenchmark.py
More file actions
365 lines (301 loc) · 9.04 KB
/
Copy pathbenchmark.py
File metadata and controls
365 lines (301 loc) · 9.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
"""
benchmark.py -
"""
import sys
import time
import json
import re
from typing import Any, Dict
import argparse
# Libraries
import pydantic
from pydantic import BaseModel, ValidationError, field_validator
import fastjsonschema
import msgspec
import validatedata as vd
print(f"Pydantic version: {pydantic.VERSION}")
print(f"validatedata version: {getattr(vd, '__version__', 'unknown')}\n")
# -----------------------------
# Config
# -----------------------------
def get_reps_warmup():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--reps", "-r", type=int, default=10_000_00,
help="Number of repetitions")
parser.add_argument("--warmup", type=int, default=5_000,
help="Warmup iterations")
if any(x in sys.modules for x in ["ipykernel", "google.colab"]):
args, _ = parser.parse_known_args()
else:
args = parser.parse_args()
return args.reps, args.warmup
REPS, WARMUP = get_reps_warmup()
print(f"Running with REPS = {REPS:,} | WARMUP = {WARMUP:,}\n")
# -----------------------------
# Test payloads
# -----------------------------
nested_valid = {
"user": {
"id": 123,
"name": "Alice",
"profile": {
"email": "alice@example.com",
"age": 30,
"address": {
"street": "Main St",
"city": "Metropolis",
"zip": "12345"
}
}
}
}
nested_invalid = {
"user": {
"id": "oops",
"name": "Alice",
"profile": {
"email": "not-an-email",
"age": "thirty",
"address": {
"street": "Main St",
"city": 999,
"zip": "ABCDE"
}
}
}
}
# -----------------------------
# Email regex for fair manual validation
# -----------------------------
EMAIL_REGEX = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
# -----------------------------
# Manual (pure Python baseline)
# -----------------------------
def manual_validate(data: Dict[str, Any]) -> bool:
try:
# Top level
if not isinstance(data, dict) or "user" not in data:
return False
user = data["user"]
if not isinstance(user, dict):
return False
# User fields
if not isinstance(user.get("id"), int):
return False
name = user.get("name")
if not isinstance(name, str) or len(name) < 1:
return False
# Profile
profile = user.get("profile")
if not isinstance(profile, dict):
return False
email = profile.get("email")
if not isinstance(email, str) or not EMAIL_REGEX.match(email):
return False
age = profile.get("age")
if not isinstance(age, int) or age < 0 or age > 120:
return False
# Address
address = profile.get("address")
if not isinstance(address, dict):
return False
street = address.get("street")
if not isinstance(street, str) or len(street) < 1:
return False
city = address.get("city")
if not isinstance(city, str) or len(city) < 1:
return False
zip_code = address.get("zip")
if not isinstance(zip_code, str) or len(zip_code) != 5:
return False
return True
except Exception:
return False
# -----------------------------
# Validatedata
# -----------------------------
vd_rules = {
"user": {
"id": "int",
"name": "str|min:1",
"profile": {
"email": "email",
"age": "int|min:0|max:120",
"address": {
"street": "str|min:1",
"city": "str|min:1",
"zip": "str|length:5"
}
}
}
}
vd_validator = vd.validator(vd_rules)
def validatedata_validate(data: Dict[str, Any]) -> bool:
try:
return bool(vd_validator(data))
except Exception:
return False
# -----------------------------
# FastModel
# -----------------------------
from validatedata import FastModel, Rule
class AddressFM(FastModel):
street: str = Rule(min=1)
city: str = Rule(min=1)
zip: str = Rule(length=5)
class ProfileFM(FastModel):
email: str = Rule("email")
age: int = Rule(min=0, max=120)
address: AddressFM
class UserFM(FastModel):
id: int
name: str = Rule(type ="str", min=1)
profile: ProfileFM
class NestedFM(FastModel):
user: UserFM
def fastmodel_validate(data):
try:
return NestedFM.from_dict(data)
except Exception:
return False
# -----------------------------
# Pydantic v2
# -----------------------------
class Address(BaseModel):
street: str
city: str
zip: str
@field_validator("zip")
@classmethod
def zip_len(cls, v: str) -> str:
if len(v) != 5:
raise ValueError("must be 5 chars")
return v
class Profile(BaseModel):
email: str
age: int
address: Address
@field_validator("email")
@classmethod
def email_has_at(cls, v: str) -> str:
if not EMAIL_REGEX.match(v):
raise ValueError("invalid email")
return v
class User(BaseModel):
id: int
name: str
profile: Profile
class NestedModel(BaseModel):
user: User
def pydantic_validate(data: Dict[str, Any]) -> bool:
try:
NestedModel.model_validate(data)
return True
except ValidationError:
return False
# -----------------------------
# fastjsonschema
# -----------------------------
json_schema = {
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string", "minLength": 1},
"profile": {
"type": "object",
"properties": {
"email": {"type": "string", "format": "email"},
"age": {"type": "integer", "minimum": 0, "maximum": 120},
"address": {
"type": "object",
"properties": {
"street": {"type": "string", "minLength": 1},
"city": {"type": "string", "minLength": 1},
"zip": {"type": "string", "minLength": 5, "maxLength": 5}
},
"required": ["street", "city", "zip"]
}
},
"required": ["email", "age", "address"]
}
},
"required": ["id", "name", "profile"]
}
},
"required": ["user"]
}
fastjson_validate = fastjsonschema.compile(json_schema)
def fastjsonschema_validate(data: Dict[str, Any]) -> bool:
try:
fastjson_validate(data)
return True
except Exception:
return False
# -----------------------------
# Msgspec - OPTIMIZED (no json.dumps)
# -----------------------------
class AddressStruct(msgspec.Struct):
street: str
city: str
zip: str
class ProfileStruct(msgspec.Struct):
email: str
age: int
address: AddressStruct
class UserStruct(msgspec.Struct):
id: int
name: str
profile: ProfileStruct
class NestedStruct(msgspec.Struct):
user: UserStruct
def msgspec_validate(data: Dict[str, Any]) -> bool:
try:
# Structural + type validation
obj = msgspec.convert(data, type=NestedStruct)
# Additional rules
if not EMAIL_REGEX.match(obj.user.profile.email):
return False
if len(obj.user.profile.address.zip) != 5:
return False
if len(obj.user.name) < 1:
return False
return True
except Exception:
return False
# -----------------------------
# Benchmark
# -----------------------------
def run_once(fn, data, reps: int):
# Warmup
for _ in range(min(WARMUP, max(100, reps // 10))):
try:
fn(data)
except:
pass
start = time.perf_counter()
ok = sum(1 for _ in range(reps) if fn(data))
end = time.perf_counter()
total = end - start
ops = reps / total if total > 0 else float("inf")
return total, ops, ok
def bench_all(data, reps: int):
size = len(json.dumps(data))
print(f"\n=== Running {reps:,} reps (~{size} bytes) ===")
for label, fn in [
("manual", manual_validate),
("validatedata_validator", validatedata_validate),
("fastmodel", fastmodel_validate),
("pydantic_v2", pydantic_validate),
("fastjsonschema", fastjsonschema_validate),
("msgspec", msgspec_validate),
]:
total, ops, ok = run_once(fn, data, reps)
print(f"{label:22s} {total:7.4f}s {ops:10,.0f} ops/s ok: {ok:,}")
if __name__ == "__main__":
print("=== VALID ===")
bench_all(nested_valid, REPS)
print("\n=== INVALID ===")
bench_all(nested_invalid, REPS)