test_example.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """示例脚本:与 --module 注入配套使用。
  2. 严格按 REQUIRE.md:
  3. 运行命令:
  4. python run_pika.py --module test_module_example test_example.py
  5. 脚本自身不负责放置模块文件;模块目录需预先存在于根目录:
  6. ./test_module_example/
  7. test_module_example.pyi
  8. test_module_example_Test.c
  9. run_pika.py 在本次运行期间会:
  10. 1. 临时复制 .pyi 与 C 到 pikapython-linux/pikapython/ 下
  11. 2. 强制(若需要)重新 cmake+预编译+编译
  12. 3. 运行后清理临时复制的文件与目录
  13. """
  14. import time
  15. import test_module_example
  16. # Python baseline implementation (for performance comparison)
  17. def py_add(a: int, b: int) -> int:
  18. return a + b
  19. obj = test_module_example.Test()
  20. # Functional checks
  21. print('[EXAMPLE] add(7, 35)=', obj.add(7, 35))
  22. print('[EXAMPLE] greet:"', obj.greet('demo'), '"', sep='')
  23. assert obj.add(1, 2) == 3
  24. assert obj.greet('x').startswith('Hello,')
  25. # Performance comparison (simplified for Pika runtime): run both versions 10000 times
  26. ITER = 10000
  27. py_total = 0.0
  28. c_total = 0.0
  29. for _ in range(ITER):
  30. t0 = time.time()
  31. py_add(123, 456)
  32. py_total += (time.time() - t0)
  33. t1 = time.time()
  34. obj.add(123, 456)
  35. c_total += (time.time() - t1)
  36. if ITER > 0:
  37. py_mean = py_total / ITER
  38. c_mean = c_total / ITER
  39. else:
  40. py_mean = 0.0
  41. c_mean = 0.0
  42. if c_mean > 0:
  43. ratio = py_mean / c_mean
  44. else:
  45. ratio = 0.0
  46. py_mean_us = py_mean * 1000000.0
  47. c_mean_us = c_mean * 1000000.0
  48. print('[PERF] python_total=' + ('%.6f' % py_total) + 's mean=' + ('%.2f' % py_mean_us) + 'us')
  49. print('[PERF] cmod_total=' + ('%.6f' % c_total) + 's mean=' + ('%.2f' % c_mean_us) + 'us')
  50. print('[PERF] speedup(py_mean/c_mean)= ' + ('%.2f' % ratio) + 'x')
  51. print('[EXAMPLE][SELFTEST] test_module_example OK')