| 1 | import time |
| 2 | import math.big |
| 3 | |
| 4 | const t = time.new_stopwatch() |
| 5 | |
| 6 | // a := big.integer_from_i64(2).pow(123123123) |
| 7 | // println(a) |
| 8 | |
| 9 | fn timed_println(msg string) { |
| 10 | timed_println_extended(t, msg) |
| 11 | } |
| 12 | |
| 13 | fn timed_println_extended(t time.StopWatch, msg string) { |
| 14 | println('${t.elapsed().microseconds():12} µs | ${msg}') |
| 15 | } |
| 16 | |
| 17 | fn f(x big.Integer, y int) big.Integer { |
| 18 | timed_println('f x y, y=${y:12}') |
| 19 | if y & 1 == 0 { |
| 20 | return f(x * x, y / 2) |
| 21 | } |
| 22 | if y == 1 { |
| 23 | return x |
| 24 | } |
| 25 | return g(x * x, y / 2, x) |
| 26 | } |
| 27 | |
| 28 | fn g(x big.Integer, y int, z big.Integer) big.Integer { |
| 29 | timed_println('g x y z, y=${y:12}') |
| 30 | if y & 1 == 0 { |
| 31 | return g(x * x, y / 2, z) |
| 32 | } |
| 33 | if y == 1 { |
| 34 | return x * z |
| 35 | } |
| 36 | return g(x * x, y / 2, x * z) |
| 37 | } |
| 38 | |
| 39 | fn calculate_and_measure(calc_label string, cb fn () big.Integer) string { |
| 40 | sw := time.new_stopwatch() |
| 41 | timed_println_extended(sw, 'start') |
| 42 | a := cb() |
| 43 | timed_println_extended(sw, 'done ${calc_label}') |
| 44 | timed_println_extended(sw, 'a.bit_len(): ${a.bit_len():12}') |
| 45 | |
| 46 | timed_println_extended(sw, 'before a.str()') |
| 47 | // s := a.hex() // hex is very fast since it does not need to do divisions at all |
| 48 | s := a.str() |
| 49 | timed_println_extended(sw, 'after a.str()') |
| 50 | dump(s.len) |
| 51 | dump(s#[0..10]) |
| 52 | dump(s#[-10..]) |
| 53 | timed_println_extended(sw, 'finish') |
| 54 | return s |
| 55 | } |
| 56 | |
| 57 | fn test_exponentiation() { |
| 58 | res1 := calculate_and_measure('f(x, y)', fn () big.Integer { |
| 59 | return f(big.integer_from_int(2), 66777) |
| 60 | }) |
| 61 | res2 := calculate_and_measure('big.int(x).pow(y)', fn () big.Integer { |
| 62 | return big.integer_from_i64(2).pow(66777) |
| 63 | }) |
| 64 | assert res1 == res2 |
| 65 | } |
| 66 | |