1 | from math import sqrt |
---|

2 | from sys import stdout as out, version_info |
---|

3 | from timeit import timeit |
---|

4 | |
---|

5 | def tester(fcns, tests): |
---|

6 | fmt = '%%-%ds %%s\n' % ( |
---|

7 | max(len(f+t) for t in tests for f in fcns), ) |
---|

8 | for fcn in fcns: |
---|

9 | for test in tests: |
---|

10 | try: |
---|

11 | trials = [ timeit(fcn+test, setup, number=10000000) |
---|

12 | for i in range(3) ] |
---|

13 | mean = sum(trials) / float(len(trials)) |
---|

14 | stdev = sqrt( sum(x**2 for x in trials)/float(len(trials)) |
---|

15 | - mean**2 ) |
---|

16 | out.write( |
---|

17 | fmt % ( fcn+test, "%0.6f +/- %0.3f" % (mean, stdev) ) ) |
---|

18 | except KeyboardInterrupt: |
---|

19 | raise SystemExit |
---|

20 | except: |
---|

21 | out.write( fmt % (fcn+test, '(exception)') ) |
---|

22 | out.flush() |
---|

23 | out.write('\n') |
---|

24 | |
---|

25 | |
---|

26 | setup=""" |
---|

27 | def f_positional(a, b, c): |
---|

28 | pass |
---|

29 | |
---|

30 | def f_varargs(*args): |
---|

31 | pass |
---|

32 | |
---|

33 | def f_default(a=None, b=5, c=None): |
---|

34 | pass |
---|

35 | |
---|

36 | def f_kwds(**kwds): |
---|

37 | pass |
---|

38 | |
---|

39 | def f_vararg_kwds(*args, **kwds): |
---|

40 | pass |
---|

41 | |
---|

42 | def f_all(a, b=5, *args, **kwds): |
---|

43 | pass |
---|

44 | |
---|

45 | pos = (1,2,3) |
---|

46 | kwd = {'a':1,'b':2,'c':3} |
---|

47 | """ |
---|

48 | |
---|

49 | p_fcns = ["f_positional", "f_varargs", "f_default", "f_vararg_kwds", "f_all"] |
---|

50 | k_fcns = ["f_positional", "f_default", "f_kwds", "f_vararg_kwds", "f_all"] |
---|

51 | #setup = "from __main__ import " + ','.join(set(p_fcns+k_fcns)) |
---|

52 | |
---|

53 | out.write('='*72+"\nTesting on Python %s\n" % ( |
---|

54 | '.'.join(str(x) for x in version_info[:3]),) ) |
---|

55 | out.write(setup) |
---|

56 | |
---|

57 | out.write("\nPositional arguments\n\n") |
---|

58 | tester(p_fcns, ['()', '(1)', '(1,2)', '(1,2,3)', '(*(1,2,3))', '(*pos)']) |
---|

59 | |
---|

60 | out.write("\nKeyword arguments\n\n") |
---|

61 | tester(k_fcns, [ '()', '(a=1)', '(a=1,b=2)', '(a=1,b=2,c=3)', |
---|

62 | "(**{'a':1,'b':2,'c':3})", "(**kwd)" ]) |
---|

63 | |
---|

64 | out.write("\nMixed arguments\n\n") |
---|

65 | tester(['f_vararg_kwds','f_all'], |
---|

66 | [ '(1,2,c=3)', '(1,b=2,c=3)', '(1,b=2)', "(1,2,3,d=4)" ]) |
---|