https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98076

--- Comment #5 from Francois-Xavier Coudert <fxcoudert at gcc dot gnu.org> ---
Consider this:

/* Fast helper function for a positive value that fits in uint64_t.  */
char *itoa64 (uint64_t n, char *p)
{
  while (n != 0)
    {
      *--p = '0' + (n % 10);
      n /= 10;
    }
  return p;
}


Then the logic inside gfc_itoa is reworked like this:

%%%%%%%%%%

  *p = '\0';

#if 1
  i (t <= UINT64_MAX) {
    p = toa64(t, p);
  } else {
    unsigned __int128 r;

#define TEN19 ((unsigned __int128) 1000000 * (unsigned __int128) 1000000 *
(unsigned __int128) 10000000)

    r = t % TEN19;
    t = t / TEN19;
    p = itoa64(r, p);

    assert(t <= UINT64_MAX);
    p = itoa64(t, p);
  }
#else
  while (t != 0)
    {
      *--p = '0' + (t % 10);
      t /= 10;
    }
#endif

  if (negative)
    *--p = '-';

  return p;

%%%%%%%%%%

where the "#if 1" branch is the new code, and the "#else" branch is the old
code. Unless I'm mistaken, two calls to itoa64() are sufficient to guarantee
that we can output all values up to INT128_MAX = 2^127 - 1. That's because
(2^127 - 1) / 10^19 is smaller than UINT64_MAX = 2^64 - 1.

We would need three calls if we wanted to output values up to UINT128_MAX =
2^128 - 1, but we don't: Fortran only deals with signed integers.



Benchmark of this code, for formatting of 10 millions numbers into a buffer:

- formatting 1042:       old code 0.31 seconds, new code 0.06 seconds
- formatting INT32_MAX:  old code 0.88 seconds, new code 0.07 seconds
- formatting INT64_MAX:  old code 1.77 seconds, new code 0.16 seconds
- formatting INT128_MAX: old code 3.74 seconds, new code 0.49 seconds


It remains to be seen how much of the actual Fortran I/O is bound by
gfc_itoa(). But the benchmarking is interesting enough that it ought to be
tried in a real example inside libgfortran, which is what I will do next.

Reply via email to