def test_replace_constants(self): def func(): return 3 self.assertNotSpecialized(func) code = func.__code__ self.assertEqual(code.co_consts, (None, 3)) code2 = fat.replace_consts(code, {3: 'new constant'}) self.assertEqual(code2.co_consts, (None, 'new constant')) code3 = fat.replace_consts(code, {'unknown': 7}) self.assertEqual(code3.co_consts, (None, 3))
The benchmark doesn't use fatoptimize, but specialize explicitly the function. """ import fat import sys def func(obj): return len(obj) if fat.get_specialized(func): print("ERROR: func() was already specialized") sys.exit(1) def func_cst(obj): return 'LEN'(obj) func_cst.__code__ = fat.replace_consts(func_cst.__code__, {'LEN': len}) def run_benchmark(bench): bench.timeit(stmt='func("abc")', globals=globals(), name='original bytecode (LOAD_GLOBAL)') bench.timeit(stmt='func_cst("abc")', globals=globals(), name='LOAD_CONST') fat.specialize(func, func_cst, [fat.GuardBuiltins(('len',))]) assert fat.get_specialized(func) bench.timeit(stmt='func("abc")', globals=globals(),
def func(obj): return mylen(obj) if fat.get_specialized(func): print("ERROR: func() was already specialized") sys.exit(1) def func_cst(obj): return 'MYLEN' (obj) func_cst.__code__ = fat.replace_consts(func_cst.__code__, {'MYLEN': mylen}) def run_benchmark(bench): bench.timeit(stmt='func("abc")', globals=globals(), name='original bytecode (LOAD_GLOBAL)') bench.timeit(stmt='func_cst("abc")', globals=globals(), name='LOAD_CONST') fat.specialize(func, func_cst, [fat.GuardGlobals(('mylen', ))]) assert fat.get_specialized(func) bench.timeit(stmt='func("abc")', globals=globals(), name='LOAD_CONST with guard on globals')
import sys mylen = len def func(obj): return mylen(obj) if fat.get_specialized(func): print("ERROR: func() was already specialized") sys.exit(1) def func_cst(obj): return "MYLEN"(obj) func_cst.__code__ = fat.replace_consts(func_cst.__code__, {"MYLEN": mylen}) def run_benchmark(bench): bench.timeit(stmt='func("abc")', globals=globals(), name="original bytecode (LOAD_GLOBAL)") bench.timeit(stmt='func_cst("abc")', globals=globals(), name="LOAD_CONST") fat.specialize(func, func_cst, [fat.GuardGlobals(("mylen",))]) assert fat.get_specialized(func) bench.timeit(stmt='func("abc")', globals=globals(), name="LOAD_CONST with guard on globals")