|
| 1 | +import sys |
| 2 | +sys.path.append("D:\\PyFastUtil") |
| 3 | +from typing import Optional |
| 4 | +from keystone import Ks, KS_ARCH_X86, KS_MODE_64 |
| 5 | +from pyfastutil.unsafe import Ptr, Unsafe, ASM |
| 6 | +import timeit |
| 7 | +from pyfastutil.native import native |
| 8 | + |
| 9 | +SIZE = 2000 |
| 10 | +REPEAT = 20 |
| 11 | + |
| 12 | +ks = Ks(KS_ARCH_X86, KS_MODE_64) |
| 13 | +asmFunc: Optional[Ptr] = None |
| 14 | + |
| 15 | + |
| 16 | +def python(n): |
| 17 | + x = 0 |
| 18 | + for i in range(n): |
| 19 | + x += i * i |
| 20 | + return x |
| 21 | + |
| 22 | + |
| 23 | +@native |
| 24 | +def native(n): |
| 25 | + x = 0 |
| 26 | + for i in range(n): |
| 27 | + x += i * i |
| 28 | + return x |
| 29 | + |
| 30 | + |
| 31 | +def setupAsm(): |
| 32 | + global asmFunc |
| 33 | + |
| 34 | + asmCode = f""" |
| 35 | + mov rax, 0 # x = 0 |
| 36 | + mov r10, 0 # i = 0 |
| 37 | + for: |
| 38 | + cmp r10, {SIZE} # if i >= {SIZE} |
| 39 | + jnl end |
| 40 | + mov r11, r10 # i * i |
| 41 | + imul r11, r11 |
| 42 | + add rax, r11 # x += i * i |
| 43 | + inc r10 # i += 1 |
| 44 | + jmp for |
| 45 | +
|
| 46 | + end: |
| 47 | + ret |
| 48 | + """ |
| 49 | + |
| 50 | + with ASM() as asm: |
| 51 | + asmFunc = asm.makeFunction(ks.asm(asmCode, as_bytes=True)[0]) |
| 52 | + |
| 53 | + |
| 54 | +def realNative(): |
| 55 | + with Unsafe() as unsafe: |
| 56 | + return unsafe.callLongLong(asmFunc) |
| 57 | + |
| 58 | + |
| 59 | +def main(): |
| 60 | + global SIZE |
| 61 | + print(f"---Python & Native & Real-Native for Benchmark---") |
| 62 | + print(f"Batch size: {SIZE}") |
| 63 | + print(f"Repeat: {REPEAT}\n") |
| 64 | + |
| 65 | + setupAsm() |
| 66 | + assert python(SIZE) == native(SIZE) == realNative() |
| 67 | + assert native.__doc__ == "<native method>" |
| 68 | + |
| 69 | + time_python = sum(timeit.repeat(lambda: python(SIZE), repeat=REPEAT, number=1)) / REPEAT |
| 70 | + time_native = sum(timeit.repeat(lambda: native(SIZE), repeat=REPEAT, number=1)) / REPEAT |
| 71 | + time_realNative = sum(timeit.repeat(realNative, repeat=REPEAT, number=1)) / REPEAT |
| 72 | + speed = time_python / time_native * 100 |
| 73 | + speed2 = time_python / time_realNative * 100 |
| 74 | + |
| 75 | + print(f"Python time: {time_python * 1000:.2f} ms") |
| 76 | + print(f"Native time: {time_native * 1000:.2f} ms") |
| 77 | + print(f"Real-Native time: {time_realNative * 1000:.2f} ms\n") |
| 78 | + print(f"Native speed of Python: {speed:.2f} %") |
| 79 | + print(f"Real-Native speed of Python: {speed2:.2f} %\n") |
| 80 | + |
| 81 | + with ASM() as asm: |
| 82 | + asm.freeFunction(asmFunc) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == '__main__': |
| 86 | + main() |
0 commit comments