test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. from ctypes import *
  2. from random import *
  3. import math
  4. import os
  5. import platform
  6. import time
  7. from enum import Enum
  8. #
  9. # Normally, we report the number of passes and fails.
  10. # With EXIT_ON_FAIL set, we exit at the first fail.
  11. #
  12. EXIT_ON_FAIL = True
  13. EXIT_ON_FAIL = False
  14. #
  15. # We skip randomized tests altogether if NO_RANDOM_TESTS is set.
  16. #
  17. NO_RANDOM_TESTS = True
  18. NO_RANDOM_TESTS = False
  19. #
  20. # If TIMED_TESTS == False and FAST_TESTS == True, we cut down the number of iterations.
  21. # See below.
  22. #
  23. FAST_TESTS = True
  24. #
  25. # For timed tests we budget a second per `n` bits and iterate until we hit that time.
  26. # Otherwise, we specify the number of iterations per bit depth in BITS_AND_ITERATIONS.
  27. #
  28. TIMED_TESTS = False
  29. TIMED_BITS_PER_SECOND = 20_000
  30. #
  31. # How many iterations of each random test do we want to run?
  32. #
  33. BITS_AND_ITERATIONS = [
  34. ( 120, 10_000),
  35. ( 1_200, 1_000),
  36. ( 4_096, 100),
  37. (12_000, 10),
  38. ]
  39. if FAST_TESTS:
  40. for k in range(len(BITS_AND_ITERATIONS)):
  41. b, i = BITS_AND_ITERATIONS[k]
  42. BITS_AND_ITERATIONS[k] = (b, i // 10 if i >= 100 else 5)
  43. if NO_RANDOM_TESTS:
  44. BITS_AND_ITERATIONS = []
  45. #
  46. # Where is the DLL? If missing, build using: `odin build . -build-mode:shared`
  47. #
  48. if platform.system() == "Windows":
  49. LIB_PATH = os.getcwd() + os.sep + "big.dll"
  50. elif platform.system() == "Linux":
  51. LIB_PATH = os.getcwd() + os.sep + "big.so"
  52. elif platform.system() == "Darwin":
  53. LIB_PATH = os.getcwd() + os.sep + "big.dylib"
  54. else:
  55. print("Platform is unsupported.")
  56. exit(1)
  57. TOTAL_TIME = 0
  58. UNTIL_TIME = 0
  59. UNTIL_ITERS = 0
  60. def we_iterate():
  61. if TIMED_TESTS:
  62. return TOTAL_TIME < UNTIL_TIME
  63. else:
  64. global UNTIL_ITERS
  65. UNTIL_ITERS -= 1
  66. return UNTIL_ITERS != -1
  67. #
  68. # Error enum values
  69. #
  70. class Error(Enum):
  71. Okay = 0
  72. Out_Of_Memory = 1
  73. Invalid_Pointer = 2
  74. Invalid_Argument = 3
  75. Unknown_Error = 4
  76. Max_Iterations_Reached = 5
  77. Buffer_Overflow = 6
  78. Integer_Overflow = 7
  79. Division_by_Zero = 8
  80. Math_Domain_Error = 9
  81. Unimplemented = 127
  82. #
  83. # Set up exported procedures
  84. #
  85. try:
  86. l = cdll.LoadLibrary(LIB_PATH)
  87. except:
  88. print("Couldn't find or load " + LIB_PATH + ".")
  89. exit(1)
  90. def load(export_name, args, res):
  91. export_name.argtypes = args
  92. export_name.restype = res
  93. return export_name
  94. #
  95. # Result values will be passed in a struct { res: cstring, err: Error }
  96. #
  97. class Res(Structure):
  98. _fields_ = [("res", c_char_p), ("err", c_uint64)]
  99. error_string = load(l.test_error_string, [c_byte], c_char_p)
  100. add = load(l.test_add, [c_char_p, c_char_p], Res)
  101. sub = load(l.test_sub, [c_char_p, c_char_p], Res)
  102. mul = load(l.test_mul, [c_char_p, c_char_p], Res)
  103. div = load(l.test_div, [c_char_p, c_char_p], Res)
  104. # Powers and such
  105. int_log = load(l.test_log, [c_char_p, c_longlong], Res)
  106. int_pow = load(l.test_pow, [c_char_p, c_longlong], Res)
  107. int_sqrt = load(l.test_sqrt, [c_char_p], Res)
  108. int_root_n = load(l.test_root_n, [c_char_p, c_longlong], Res)
  109. # Logical operations
  110. int_shl_digit = load(l.test_shl_digit, [c_char_p, c_longlong], Res)
  111. int_shr_digit = load(l.test_shr_digit, [c_char_p, c_longlong], Res)
  112. int_shl = load(l.test_shl, [c_char_p, c_longlong], Res)
  113. int_shr = load(l.test_shr, [c_char_p, c_longlong], Res)
  114. int_shr_signed = load(l.test_shr_signed, [c_char_p, c_longlong], Res)
  115. int_factorial = load(l.test_factorial, [c_uint64], Res)
  116. int_gcd = load(l.test_gcd, [c_char_p, c_char_p], Res)
  117. def test(test_name: "", res: Res, param=[], expected_error = Error.Okay, expected_result = "", radix=16):
  118. passed = True
  119. r = None
  120. err = Error(res.err)
  121. if err != expected_error:
  122. error_loc = res.res.decode('utf-8')
  123. error = "{}: {} in '{}'".format(test_name, err, error_loc)
  124. if len(param):
  125. error += " with params {}".format(param)
  126. print(error, flush=True)
  127. passed = False
  128. elif err == Error.Okay:
  129. r = None
  130. try:
  131. r = res.res.decode('utf-8')
  132. r = int(res.res, radix)
  133. except:
  134. pass
  135. if r != expected_result:
  136. error = "{}: Result was '{}', expected '{}'".format(test_name, r, expected_result)
  137. if len(param):
  138. error += " with params {}".format(param)
  139. print(error, flush=True)
  140. passed = False
  141. if EXIT_ON_FAIL and not passed: exit(res.err)
  142. return passed
  143. def arg_to_odin(a):
  144. if a >= 0:
  145. s = hex(a)[2:]
  146. else:
  147. s = '-' + hex(a)[3:]
  148. return s.encode('utf-8')
  149. def test_add(a = 0, b = 0, expected_error = Error.Okay):
  150. args = [arg_to_odin(a), arg_to_odin(b)]
  151. res = add(*args)
  152. expected_result = None
  153. if expected_error == Error.Okay:
  154. expected_result = a + b
  155. return test("test_add", res, [a, b], expected_error, expected_result)
  156. def test_sub(a = 0, b = 0, expected_error = Error.Okay):
  157. args = [arg_to_odin(a), arg_to_odin(b)]
  158. res = sub(*args)
  159. expected_result = None
  160. if expected_error == Error.Okay:
  161. expected_result = a - b
  162. return test("test_sub", res, [a, b], expected_error, expected_result)
  163. def test_mul(a = 0, b = 0, expected_error = Error.Okay):
  164. args = [arg_to_odin(a), arg_to_odin(b)]
  165. res = mul(*args)
  166. expected_result = None
  167. if expected_error == Error.Okay:
  168. expected_result = a * b
  169. return test("test_mul", res, [a, b], expected_error, expected_result)
  170. def test_div(a = 0, b = 0, expected_error = Error.Okay):
  171. args = [arg_to_odin(a), arg_to_odin(b)]
  172. res = div(*args)
  173. expected_result = None
  174. if expected_error == Error.Okay:
  175. #
  176. # We don't round the division results, so if one component is negative, we're off by one.
  177. #
  178. if a < 0 and b > 0:
  179. expected_result = int(-(abs(a) // b))
  180. elif b < 0 and a > 0:
  181. expected_result = int(-(a // abs((b))))
  182. else:
  183. expected_result = a // b if b != 0 else None
  184. return test("test_div", res, [a, b], expected_error, expected_result)
  185. def test_log(a = 0, base = 0, expected_error = Error.Okay):
  186. args = [arg_to_odin(a), base]
  187. res = int_log(*args)
  188. expected_result = None
  189. if expected_error == Error.Okay:
  190. expected_result = int(math.log(a, base))
  191. return test("test_log", res, [a, base], expected_error, expected_result)
  192. def test_pow(base = 0, power = 0, expected_error = Error.Okay):
  193. args = [arg_to_odin(base), power]
  194. res = int_pow(*args)
  195. expected_result = None
  196. if expected_error == Error.Okay:
  197. if power < 0:
  198. expected_result = 0
  199. else:
  200. # NOTE(Jeroen): Don't use `math.pow`, it's a floating point approximation.
  201. # Use built-in `pow` or `a**b` instead.
  202. expected_result = pow(base, power)
  203. return test("test_pow", res, [base, power], expected_error, expected_result)
  204. def test_sqrt(number = 0, expected_error = Error.Okay):
  205. args = [arg_to_odin(number)]
  206. res = int_sqrt(*args)
  207. expected_result = None
  208. if expected_error == Error.Okay:
  209. if number < 0:
  210. expected_result = 0
  211. else:
  212. expected_result = int(math.isqrt(number))
  213. return test("test_sqrt", res, [number], expected_error, expected_result)
  214. def root_n(number, root):
  215. u, s = number, number + 1
  216. while u < s:
  217. s = u
  218. t = (root-1) * s + number // pow(s, root - 1)
  219. u = t // root
  220. return s
  221. def test_root_n(number = 0, root = 0, expected_error = Error.Okay):
  222. args = [arg_to_odin(number), root]
  223. res = int_root_n(*args)
  224. expected_result = None
  225. if expected_error == Error.Okay:
  226. if number < 0:
  227. expected_result = 0
  228. else:
  229. expected_result = root_n(number, root)
  230. return test("test_root_n", res, [number, root], expected_error, expected_result)
  231. def test_shl_digit(a = 0, digits = 0, expected_error = Error.Okay):
  232. args = [arg_to_odin(a), digits]
  233. res = int_shl_digit(*args)
  234. expected_result = None
  235. if expected_error == Error.Okay:
  236. expected_result = a << (digits * 60)
  237. return test("test_shl_digit", res, [a, digits], expected_error, expected_result)
  238. def test_shr_digit(a = 0, digits = 0, expected_error = Error.Okay):
  239. args = [arg_to_odin(a), digits]
  240. res = int_shr_digit(*args)
  241. expected_result = None
  242. if expected_error == Error.Okay:
  243. if a < 0:
  244. # Don't pass negative numbers. We have a shr_signed.
  245. return False
  246. else:
  247. expected_result = a >> (digits * 60)
  248. return test("test_shr_digit", res, [a, digits], expected_error, expected_result)
  249. def test_shl(a = 0, bits = 0, expected_error = Error.Okay):
  250. args = [arg_to_odin(a), bits]
  251. res = int_shl(*args)
  252. expected_result = None
  253. if expected_error == Error.Okay:
  254. expected_result = a << bits
  255. return test("test_shl", res, [a, bits], expected_error, expected_result)
  256. def test_shr(a = 0, bits = 0, expected_error = Error.Okay):
  257. args = [arg_to_odin(a), bits]
  258. res = int_shr(*args)
  259. expected_result = None
  260. if expected_error == Error.Okay:
  261. if a < 0:
  262. # Don't pass negative numbers. We have a shr_signed.
  263. return False
  264. else:
  265. expected_result = a >> bits
  266. return test("test_shr", res, [a, bits], expected_error, expected_result)
  267. def test_shr_signed(a = 0, bits = 0, expected_error = Error.Okay):
  268. args = [arg_to_odin(a), bits]
  269. res = int_shr_signed(*args)
  270. expected_result = None
  271. if expected_error == Error.Okay:
  272. expected_result = a >> bits
  273. return test("test_shr_signed", res, [a, bits], expected_error, expected_result)
  274. def test_factorial(n = 0, expected_error = Error.Okay):
  275. args = [n]
  276. res = int_factorial(*args)
  277. expected_result = None
  278. if expected_error == Error.Okay:
  279. expected_result = math.factorial(n)
  280. return test("test_factorial", res, [n], expected_error, expected_result)
  281. def test_gcd(a = 0, b = 0, expected_error = Error.Okay):
  282. args = [arg_to_odin(a), arg_to_odin(b)]
  283. res = int_gcd(*args)
  284. expected_result = None
  285. if expected_error == Error.Okay:
  286. expected_result = math.gcd(a, b)
  287. return test("test_gcd", res, [a, b], expected_error, expected_result)
  288. # TODO(Jeroen): Make sure tests cover edge cases, fast paths, and so on.
  289. #
  290. # The last two arguments in tests are the expected error and expected result.
  291. #
  292. # The expected error defaults to None.
  293. # By default the Odin implementation will be tested against the Python one.
  294. # You can override that by supplying an expected result as the last argument instead.
  295. TESTS = {
  296. test_add: [
  297. [ 1234, 5432],
  298. ],
  299. test_sub: [
  300. [ 1234, 5432],
  301. ],
  302. test_mul: [
  303. [ 1234, 5432],
  304. [ 0xd3b4e926aaba3040e1c12b5ea553b5, 0x1a821e41257ed9281bee5bc7789ea7]
  305. ],
  306. test_div: [
  307. [ 54321, 12345],
  308. [ 55431, 0, Error.Division_by_Zero],
  309. [ 12980742146337069150589594264770969721, 4611686018427387904 ],
  310. ],
  311. test_log: [
  312. [ 3192, 1, Error.Invalid_Argument],
  313. [ -1234, 2, Error.Math_Domain_Error],
  314. [ 0, 2, Error.Math_Domain_Error],
  315. [ 1024, 2],
  316. ],
  317. test_pow: [
  318. [ 0, -1, Error.Math_Domain_Error ], # Math
  319. [ 0, 0 ], # 1
  320. [ 0, 2 ], # 0
  321. [ 42, -1,], # 0
  322. [ 42, 1 ], # 1
  323. [ 42, 0 ], # 42
  324. [ 42, 2 ], # 42*42
  325. ],
  326. test_sqrt: [
  327. [ -1, Error.Invalid_Argument, ],
  328. [ 42, Error.Okay, ],
  329. [ 12345678901234567890, Error.Okay, ],
  330. [ 1298074214633706907132624082305024, Error.Okay, ],
  331. ],
  332. test_root_n: [
  333. [ 1298074214633706907132624082305024, 2, Error.Okay, ],
  334. ],
  335. test_shl_digit: [
  336. [ 3192, 1 ],
  337. [ 1298074214633706907132624082305024, 2 ],
  338. [ 1024, 3 ],
  339. ],
  340. test_shr_digit: [
  341. [ 3680125442705055547392, 1 ],
  342. [ 1725436586697640946858688965569256363112777243042596638790631055949824, 2 ],
  343. [ 219504133884436710204395031992179571, 2 ],
  344. ],
  345. test_shl: [
  346. [ 3192, 1 ],
  347. [ 1298074214633706907132624082305024, 2 ],
  348. [ 1024, 3 ],
  349. ],
  350. test_shr: [
  351. [ 3680125442705055547392, 1 ],
  352. [ 1725436586697640946858688965569256363112777243042596638790631055949824, 2 ],
  353. [ 219504133884436710204395031992179571, 2 ],
  354. ],
  355. test_shr_signed: [
  356. [ -611105530635358368578155082258244262, 12 ],
  357. [ -149195686190273039203651143129455, 12 ],
  358. [ 611105530635358368578155082258244262, 12 ],
  359. [ 149195686190273039203651143129455, 12 ],
  360. ],
  361. test_factorial: [
  362. [ 12_345 ],
  363. ],
  364. test_gcd: [
  365. [ 123, 25, ],
  366. [ 125, 25, ],
  367. ],
  368. }
  369. total_passes = 0
  370. total_failures = 0
  371. #
  372. # test_shr_signed also tests shr, so we're not going to test shr randomly.
  373. #
  374. RANDOM_TESTS = [
  375. test_add, test_sub, test_mul, test_div,
  376. test_log, test_pow, test_sqrt, test_root_n,
  377. test_shl_digit, test_shr_digit, test_shl, test_shr_signed,
  378. test_gcd,
  379. ]
  380. SKIP_LARGE = [
  381. test_pow, test_root_n, # test_gcd,
  382. ]
  383. SKIP_LARGEST = []
  384. # Untimed warmup.
  385. for test_proc in TESTS:
  386. for t in TESTS[test_proc]:
  387. res = test_proc(*t)
  388. if __name__ == '__main__':
  389. print("---- math/big tests ----")
  390. print()
  391. for test_proc in TESTS:
  392. count_pass = 0
  393. count_fail = 0
  394. TIMINGS = {}
  395. for t in TESTS[test_proc]:
  396. start = time.perf_counter()
  397. res = test_proc(*t)
  398. diff = time.perf_counter() - start
  399. TOTAL_TIME += diff
  400. if test_proc not in TIMINGS:
  401. TIMINGS[test_proc] = diff
  402. else:
  403. TIMINGS[test_proc] += diff
  404. if res:
  405. count_pass += 1
  406. total_passes += 1
  407. else:
  408. count_fail += 1
  409. total_failures += 1
  410. print("{name}: {count_pass:,} passes and {count_fail:,} failures in {timing:.3f} ms.".format(name=test_proc.__name__, count_pass=count_pass, count_fail=count_fail, timing=TIMINGS[test_proc] * 1_000))
  411. for BITS, ITERATIONS in BITS_AND_ITERATIONS:
  412. print()
  413. print("---- math/big with two random {bits:,} bit numbers ----".format(bits=BITS))
  414. print()
  415. for test_proc in RANDOM_TESTS:
  416. if BITS > 1_200 and test_proc in SKIP_LARGE: continue
  417. if BITS > 4_096 and test_proc in SKIP_LARGEST: continue
  418. count_pass = 0
  419. count_fail = 0
  420. TIMINGS = {}
  421. UNTIL_ITERS = ITERATIONS
  422. if test_proc == test_root_n and BITS == 1_200:
  423. UNTIL_ITERS /= 10
  424. UNTIL_TIME = TOTAL_TIME + BITS / TIMED_BITS_PER_SECOND
  425. # We run each test for a second per 20k bits
  426. while we_iterate():
  427. a = randint(-(1 << BITS), 1 << BITS)
  428. b = randint(-(1 << BITS), 1 << BITS)
  429. if test_proc == test_div:
  430. # We've already tested division by zero above.
  431. bits = int(BITS * 0.6)
  432. b = randint(-(1 << bits), 1 << bits)
  433. if b == 0:
  434. b == 42
  435. elif test_proc == test_log:
  436. # We've already tested log's domain errors.
  437. a = randint(1, 1 << BITS)
  438. b = randint(2, 1 << 60)
  439. elif test_proc == test_pow:
  440. b = randint(1, 10)
  441. elif test_proc == test_sqrt:
  442. a = randint(1, 1 << BITS)
  443. b = Error.Okay
  444. elif test_proc == test_root_n:
  445. a = randint(1, 1 << BITS)
  446. b = randint(1, 10);
  447. elif test_proc == test_shl_digit:
  448. b = randint(0, 10);
  449. elif test_proc == test_shr_digit:
  450. a = abs(a)
  451. b = randint(0, 10);
  452. elif test_proc == test_shl:
  453. b = randint(0, min(BITS, 120));
  454. elif test_proc == test_shr_signed:
  455. b = randint(0, min(BITS, 120));
  456. else:
  457. b = randint(0, 1 << BITS)
  458. res = None
  459. start = time.perf_counter()
  460. res = test_proc(a, b)
  461. diff = time.perf_counter() - start
  462. TOTAL_TIME += diff
  463. if test_proc not in TIMINGS:
  464. TIMINGS[test_proc] = diff
  465. else:
  466. TIMINGS[test_proc] += diff
  467. if res:
  468. count_pass += 1; total_passes += 1
  469. else:
  470. count_fail += 1; total_failures += 1
  471. print("{name}: {count_pass:,} passes and {count_fail:,} failures in {timing:.3f} ms.".format(name=test_proc.__name__, count_pass=count_pass, count_fail=count_fail, timing=TIMINGS[test_proc] * 1_000))
  472. print()
  473. print("---- THE END ----")
  474. print()
  475. print("total: {count_pass:,} passes and {count_fail:,} failures in {timing:.3f} ms.".format(count_pass=total_passes, count_fail=total_failures, timing=TOTAL_TIME * 1_000))
  476. if total_failures:
  477. exit(1)