#!/usr/bin/env python # -*- coding: utf-8 -*- from itertools import islice from random import random import timeit from superfastcode_cpython import fast_tanh from superfastcode_boost import boost_tanh COUNT = 500000 # Change this value depending on the speed of your computer NUM_OF_EXEC = 30 DATA = list(islice(iter(lambda: (random() - 0.5) * 3.0, None), COUNT)) e = 2.7182818284590452353602874713527 def sinh(x): return (1 - (e ** (-2 * x))) / (2 * (e ** -x)) def cosh(x): return (1 + (e ** (-2 * x))) / (2 * (e ** -x)) def tanh(x): tanh_x = sinh(x) / cosh(x) return tanh_x def test(fn, name): # timeit monkey-patching timeit.template = """ def inner(_it, _timer{init}): {setup} _t0 = _timer() for _i in _it: retval = {stmt} _t1 = _timer() return _t1 - _t0, retval """ duration, result = timeit.timeit(lambda: fn(DATA), number=NUM_OF_EXEC) duration = duration / NUM_OF_EXEC print(f'{name} took {duration:.3f} seconds') for d in result: assert -1 <= d <= 1, " incorrect values" def main(): print(f'Running benchmarks with COUNT = {COUNT} x NUM_OF_EXEC = {NUM_OF_EXEC}') test(lambda d: [tanh(x) for x in d], '[tanh(x) for x in d] (Python implementation)') test(lambda d: [fast_tanh(x) for x in d], '[fast_tanh(x) for x in d] (CPython C++ implementation)') test(lambda d: [boost_tanh(x) for x in d], '[boost_tanh(x) for x in d] (Boost.Python C++ implementation)') if __name__ == "__main__": main()