AndreaCensi / contracts

PyContracts is a Python package that allows to declare constraints on function parameters and return values. Contracts can be specified using Python3 annotations, or inside a docstring. PyContracts supports a basic type system, variables binding, arithmetic constraints, and has several specialized contracts and an extension API.
http://andreacensi.github.io/contracts/
Other
398 stars 62 forks source link

Runtime is ~an order of magnitude slower than manual constraint writing #74

Open rht opened 5 years ago

rht commented 5 years ago

I tested this on my machine

import time
from contracts import contract

@contract(a='int,>0', b='list[N],N>0', returns='list[N]')
def c(a, b):
    return [a * i for i in b]

def d(a, b):
    assert isinstance(a, int)
    assert a > 0
    assert isinstance(b, list)
    assert len(b) > 0
    out = [a * i for i in b]
    assert len(out) == len(b)
    return out

tic = time.time()
x = list(range(100))
for i in range(1000):
    x = c(5, x)
tic2 = time.time()
print(tic2-tic)
x = list(range(100))
for i in range(1000):
    x = d(5, x)
tic3 = time.time()
print(tic3-tic2)

Found the result to be

$ python ttest.py
0.5048160552978516
0.07861089706420898

Are there any additional checks that are missing in my manual implementation?