Commit e142bfe8

e142bfe8ef95Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · ~1 modified

Description

perf: use mpz_get_str for bigint to_s (4x faster on large numbers)

Replace sp_bigint_to_s's naive O(n^2) repeated-division-by-10 with the existing mpz_get_str which dispatches to:

  • CPython-style base conversion for medium numbers
  • Divide-and-conquer O(n log^2 n) for large numbers (>700 digits)

Both algorithms were already implemented in the mpz codebase (from mruby-bigint) but sp_bigint_to_s was not using them.

fib(100000) to_s: 0.32s → ~0s (4x+ speedup, no longer the bottleneck) factorial(100) and fib(1000) output matches Ruby exactly.

No GMP dependency needed — this is pure mruby-bigint.

75/75 tests pass.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
e142bfe8ef95
Parent
6d3a86bac528

lib/sp_bigint.cmodifiedView file

@@ -5378,29 +5378,17 @@
53785378 snprintf(s, 24, "%lld", (long long)v);
53795379 return s;
53805380 }
5381- /* Large number: use mpz_sizeinbase for allocation, repeated div/mod for digits */
5382- size_t est = mpz_sizeinbase(z, 10) + 2;
5383- char *buf = (char*)malloc(est + 1);
5384- char *p = buf + est;
5385- *p = 0;
5386- mpz_t tmp, rem, ten;
5387- mpz_init_set(sp_mpz_ctx, &tmp, z);
5388- if (tmp.sn < 0) tmp.sn = 1;
5389- mpz_init_set_int(sp_mpz_ctx, &ten, 10);
5390- mpz_init(sp_mpz_ctx, &rem);
5391- while (tmp.sz > 0 && !(tmp.sz == 1 && tmp.p[0] == 0)) {
5392- mpz_mmod(sp_mpz_ctx, &rem, &tmp, &ten);
5393- int digit = (rem.sz > 0) ? (int)(rem.p[0]) : 0;
5394- *--p = '0' + digit;
5395- mpz_mdiv(sp_mpz_ctx, &tmp, &tmp, &ten);
5396- }
5397- if (*p == 0) *--p = '0';
5398- if (z->sn < 0) *--p = '-';
5399- char *result = (char*)malloc(strlen(p) + 1);
5400- strcpy(result, p);
5401- mpz_clear(sp_mpz_ctx, &tmp);
5402- mpz_clear(sp_mpz_ctx, &ten);
5403- mpz_clear(sp_mpz_ctx, &rem);
5381+ /* Use mpz_get_str which dispatches to:
5382+ * - CPython-style base conversion for medium numbers
5383+ * - Divide-and-conquer (O(n log^2 n)) for large numbers
5384+ * Much faster than the naive repeated-div-by-10 loop. */
5385+ size_t est = mpz_sizeinbase(z, 10) + 4;
5386+ char *buf = (char*)malloc(est);
5387+ mpz_get_str(sp_mpz_ctx, buf, (mrb_int)est, 10, z);
5388+ /* mpz_get_str writes into buf; return a trimmed copy */
5389+ size_t len = strlen(buf);
5390+ char *result = (char*)malloc(len + 1);
5391+ memcpy(result, buf, len + 1);
54045392 free(buf);
54055393 return result;
54065394 }