Hacker News

Counting large numbers of events in small floating point registers

Comments

In 1978, the ACM published an algorithm by Robert Morris for counting large numbers of events in small registers. It uses one byte to keep track of the approximate logarithm of the count, and randomly increments the logarithm with a probability that scales with the value of the count.

You can tune the range and precision of the counter by adjusting the base of the logarithm. Morris suggests pre-calculating a table of probabilities so that no difficult calculations are needed at runtime.

Recently I learned from emsenn about a 2009 paper by Miklós Csűrös titled approximate counting with a floating-point counter. It changes Morris's algorithm to use a binary log-linear counter instead of a pure logarithm. It reminded me of my hg64 log-linear histograms, so I thought it would be fun to implement, especially since the algorithm can be made shorter and faster.

Representing a counter

We need to choose the number of bits to use for the exponent and mantissa of each approximate floating point counter. Typically the exponent will be 5 or 6 bits, corresponding to an unpacked exact counter of 32 or 64 bits. The mantissa will typically be the rest of an 8 or 16 bit integer (though languages such as Zig and C23 allow more adventurous integer sizes).

I'll call the approximate counter type usmol and the unpacked counter type ubig.

#define EXPBITS 5
#define SIGBITS 3
typedef unsigned _BitInt(EXPBITS+SIGBITS) usmol;
typedef uint32_t ubig;
static_assert(sizeof(ubig) * 8 == 1 = e));
}

Considerations

Morris allows you to smoothly tune the allowable range and precision of a counter by adjusting the base of the logarithm. By contrast, Csűrös has very lumpy 2^2^n choice of ranges; that isn't necessarily bad because it's normal for programmers to have to choose between uint32_t and uint64_t.

Morris uses a lookup table to determine the probability of incrementing, which is tolerable for an 8 bit counter, but it can get large for wider counters. Csűrös just uses a few instructions and bigger counters don't need much more.

So I don't think either algorithm is clearly better than the other, except that Csűrös has the winning fun factor of bithacking a bespoke floating point format.

Read on Hacker News ↗ ← Back to News

Comments

No comments yet. Start the discussion.