Skip to content

Instantly share code, notes, and snippets.

@munificent
Created July 27, 2019 20:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munificent/b4a733baab60ecb3a3cbd275f6e27446 to your computer and use it in GitHub Desktop.
Save munificent/b4a733baab60ecb3a3cbd275f6e27446 to your computer and use it in GitHub Desktop.
Dump a PPM image of a Wren map's hash buckets
// Generates a PPM image showing the entries in a Wren Map.
//
// Each pixel represents an entry. It will be black if the entry is empty is
// empty. Otherwise, it will be some other color. The red and green channels
// represents how far the key in that entry is from where it would ideally be.
// In other words, how many collisions occurred before it could be inserted.
// Brighter colors are worse. In particular, brighter green colors are much
// worse.
//
// A good hashing function will lead to an image containing a random-looking
// noise of black and dark blue pixels. A bad function will show clear patterns.
// If there are many brighter and greener pixels, then the map's performance is
// degrading from collisions.
void wrenMapDumpImage(ObjMap* map)
{
char filename[100];
sprintf(filename, "map%d.ppm", map->count);
FILE *fp = fopen(filename, "wb");
int width = 1024;
int height = map->capacity / 1024;
fprintf(fp, "P6\n%d %d\n255\n", width, height);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
static unsigned char color[3];
color[0] = 0; /* red */
color[1] = 0; /* green */
color[2] = 0; /* blue */
int32_t index = y * width + x;
MapEntry* entry = &map->entries[index];
if (!IS_UNDEFINED(entry->key))
{
int32_t ideal = hashValue(entry->key) % map->capacity;
int64_t distance = (int64_t)index - (int64_t)ideal;
if (distance < 0) distance += map->capacity;
color[0] = distance % 255;
color[1] = (distance / 255) % 255;
color[2] = 128;
}
fwrite(color, 1, 3, fp);
}
}
fclose(fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment