Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * textbench.c - text rendering speed prototype
- *
- * AI-generated, human-reviewed and edited.
- *
- * Renders a grid of ASCII characters into a 3840x2160 32-bit buffer that lives in SysV shared memory.
- * Renders 15 times, ignores the first 5, reports timing to stderr, then
- * shows the buffer in an X window via MIT-SHM.
- *
- * Debian dependencies: sudo apt install build-essential pkg-config libfreetype-dev libx11-dev libxext-dev fonts-dejavu-core
- *
- * Build:
- * gcc -O2 -Wall -o textbench textbench.c $(pkg-config --cflags --libs freetype2) -lX11 -lXext
- *
- * You may use -O3 -march=native for better performance.
- *
- * Run:
- * ./textbench [path/to/font.ttf]
- */
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <X11/Xlib.h>
- #include <X11/Xutil.h>
- #include <X11/extensions/XShm.h>
- #include <ft2build.h>
- #include FT_FREETYPE_H
- /* ---------- Geometry ---------- */
- #define SCREEN_W 3840
- #define SCREEN_H 2160
- #define CELL_W 13 /* glyph box width */
- #define CELL_H 24 /* glyph box height */
- #define LINE_H 24 /* distance between text lines */
- #define COLS (SCREEN_W / CELL_W) /* 240 */
- #define ROWS (SCREEN_H / LINE_H) /* 108 */
- #define BUF_PIXELS ((size_t)SCREEN_W * SCREEN_H)
- #define BUF_BYTES (BUF_PIXELS * sizeof(uint32_t))
- /* ---------- Text / font ---------- */
- #define FIRST_CHAR 32 /* ' ' */
- #define LAST_CHAR 126 /* '~' */
- #define NUM_CHARS (LAST_CHAR - FIRST_CHAR + 1)
- #define FONT_PIXEL_SIZE 20
- /* ---------- Colours (0x00RRGGBB) ---------- */
- #define FG_COLOR 0x00FFFFFFu
- #define BG_COLOR 0x00000000u
- /* ---------- Benchmark ---------- */
- #define WARMUP_RUNS 5
- #define MEASURED_RUNS 10
- static const char *font_candidates[] = {
- "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
- "/usr/share/fonts/TTF/DejaVuSansMono.ttf",
- "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
- NULL
- };
- /* Glyph cache: 8-bit coverage (alpha) per pixel of each 16x16 cell. */
- static uint8_t glyph_cache[NUM_CHARS][CELL_H][CELL_W];
- /* Fixed-size 2D text grid. */
- static unsigned char text[ROWS][COLS];
- static void die(const char *msg)
- {
- fprintf(stderr, "error: %s\n", msg);
- exit(EXIT_FAILURE);
- }
- static const char *find_font(void)
- {
- for (int i = 0; font_candidates[i]; i++) {
- FILE *f = fopen(font_candidates[i], "rb");
- if (f) {
- fclose(f);
- return font_candidates[i];
- }
- }
- return NULL;
- }
- /* Rasterize all printable ASCII characters into the 16x16 glyph cache. */
- static void build_glyph_cache(const char *fontpath)
- {
- FT_Library lib;
- FT_Face face;
- if (FT_Init_FreeType(&lib))
- die("FT_Init_FreeType failed");
- if (FT_New_Face(lib, fontpath, 0, &face))
- die("could not load font file (pass one as argument)");
- if (FT_Set_Pixel_Sizes(face, 0, FONT_PIXEL_SIZE))
- die("FT_Set_Pixel_Sizes failed");
- /* Baseline position inside the 16 px cell, in whole pixels. */
- const int baseline = (int)(face->size->metrics.ascender >> 6);
- for (int c = FIRST_CHAR; c <= LAST_CHAR; c++) {
- uint8_t (*cell)[CELL_W] = glyph_cache[c - FIRST_CHAR];
- memset(cell, 0, CELL_W * CELL_H);
- if (FT_Load_Char(face, c, FT_LOAD_RENDER))
- continue;
- const FT_Bitmap *bm = &face->glyph->bitmap;
- const int ox = face->glyph->bitmap_left;
- const int oy = baseline - face->glyph->bitmap_top;
- for (unsigned int y = 0; y < bm->rows; y++) {
- int dy = oy + (int)y;
- if (dy < 0 || dy >= CELL_H)
- continue;
- for (unsigned int x = 0; x < bm->width; x++) {
- int dx = ox + (int)x;
- if (dx < 0 || dx >= CELL_W)
- continue;
- cell[dy][dx] = bm->buffer[y * bm->pitch + x];
- }
- }
- }
- FT_Done_Face(face);
- FT_Done_FreeType(lib);
- }
- /* Fill the text grid with printable ASCII in order, wrapping around. */
- static void generate_text(void)
- {
- for (int r = 0; r < ROWS; r++)
- for (int c = 0; c < COLS; c++)
- text[r][c] = (unsigned char)(FIRST_CHAR + ((size_t)r * COLS + c) % NUM_CHARS);
- }
- /* Alpha-blend src over dst, per channel. */
- static inline uint32_t blend(uint32_t dst, uint32_t src, uint8_t a)
- {
- const uint32_t ia = 255u - a;
- const uint32_t r = ((src >> 16 & 0xFF) * a + (dst >> 16 & 0xFF) * ia) / 255u;
- const uint32_t g = ((src >> 8 & 0xFF) * a + (dst >> 8 & 0xFF) * ia) / 255u;
- const uint32_t b = ((src & 0xFF) * a + (dst & 0xFF) * ia) / 255u;
- return (r << 16) | (g << 8) | b;
- }
- /* Render the whole text grid into the framebuffer. Every cell is blended
- * (no early-out on zero alpha) so the cost per letter is constant. */
- static void render_text(uint32_t *buf)
- {
- for (size_t i = 0; i < BUF_PIXELS; i++) {
- buf[i] = BG_COLOR;
- }
- for (int row = 0; row < ROWS; row++) {
- for (int col = 0; col < COLS; col++) {
- const int idx = text[row][col] - FIRST_CHAR;
- const int x0 = col * CELL_W;
- const int y0 = row * LINE_H;
- for (int y = 0; y < CELL_H; y++) {
- uint32_t *dst = buf + (size_t)(y0 + y) * SCREEN_W + x0;
- const uint8_t *src = glyph_cache[idx][y];
- for (int x = 0; x < CELL_W; x++)
- dst[x] = blend(/* dst[x] */BG_COLOR, FG_COLOR, src[x]);
- }
- }
- }
- }
- static double elapsed_ns(const struct timespec *a, const struct timespec *b)
- {
- return (double)(b->tv_sec - a->tv_sec) * 1e9 + (double)(b->tv_nsec - a->tv_nsec);
- }
- static void run_benchmark(uint32_t *buf)
- {
- const long long letters_per_frame = (long long)COLS * ROWS;
- const long long pixels_per_frame = (long long)BUF_PIXELS;
- double total_ns = 0.0;
- for (int run = 0; run < WARMUP_RUNS + MEASURED_RUNS; run++) {
- struct timespec t0, t1;
- clock_gettime(CLOCK_MONOTONIC, &t0);
- render_text(buf);
- clock_gettime(CLOCK_MONOTONIC, &t1);
- if (run >= WARMUP_RUNS) {
- total_ns += elapsed_ns(&t0, &t1);
- }
- }
- const double total_s = total_ns / 1e9;
- const double total_letters = (double)letters_per_frame * MEASURED_RUNS;
- const double total_pixels = (double)pixels_per_frame * MEASURED_RUNS;
- fprintf(stderr, "\n=== Text rendering benchmark ===\n");
- fprintf(stderr, "Buffer: %d x %d px (%zu bytes)\n",
- SCREEN_W, SCREEN_H, BUF_BYTES);
- fprintf(stderr, "Grid: %d cols x %d rows = %lld letters/frame\n",
- COLS, ROWS, letters_per_frame);
- fprintf(stderr, "Measured runs: %d (first %d ignored)\n",
- MEASURED_RUNS, WARMUP_RUNS);
- fprintf(stderr, "Total time: %.3f ms\n", total_ns / 1e6);
- fprintf(stderr, "Avg per frame: %.3f ms\n",
- total_ns / 1e6 / MEASURED_RUNS);
- fprintf(stderr, "Time per letter: %.1f ns\n", total_ns / total_letters);
- fprintf(stderr, "Letters/second: %.0f\n", total_letters / total_s);
- fprintf(stderr, "Pixels/second: %.3f Mpx/s\n",
- total_pixels / total_s / 1e6);
- fprintf(stderr, "Note: pixels are full buffer pixels (background clear\n included); letters are grid cells incl. spaces.\n\n");
- }
- int main(int argc, char **argv)
- {
- const char *font = (argc > 1) ? argv[1] : find_font();
- if (!font)
- die("no font found; pass a .ttf path as the first argument");
- /* Allocate the frame buffer in SysV shared memory from the start. */
- int shmid = shmget(IPC_PRIVATE, BUF_BYTES, IPC_CREAT | 0600);
- if (shmid < 0)
- die("shmget failed");
- uint32_t *buf = shmat(shmid, NULL, 0);
- if (buf == (void *)-1)
- die("shmat failed");
- build_glyph_cache(font);
- generate_text();
- run_benchmark(buf);
- /* ---------- X11 display via MIT-SHM ---------- */
- Display *dpy = XOpenDisplay(NULL);
- if (!dpy)
- die("cannot open X display");
- if (!XShmQueryExtension(dpy))
- die("X server does not support MIT-SHM");
- int scr = DefaultScreen(dpy);
- int depth = DefaultDepth(dpy, scr);
- if (depth != 24)
- die("this prototype expects a 24-bit default visual");
- XShmSegmentInfo shminfo;
- memset(&shminfo, 0, sizeof(shminfo));
- shminfo.shmid = shmid;
- shminfo.shmaddr = (char *)buf;
- shminfo.readOnly = False;
- XImage *img = XShmCreateImage(dpy, DefaultVisual(dpy, scr), depth,
- ZPixmap, NULL, &shminfo,
- SCREEN_W, SCREEN_H);
- if (!img)
- die("XShmCreateImage failed");
- if (img->bits_per_pixel != 32)
- die("expected 32 bits per pixel XImage");
- img->data = (char *)buf; /* point the XImage at our shared buffer */
- if (!XShmAttach(dpy, &shminfo))
- die("XShmAttach failed");
- XSync(dpy, False);
- /* Segment is destroyed once everyone detaches; ensures cleanup. */
- shmctl(shmid, IPC_RMID, NULL);
- /* Clamp window to the display so it stays visible. */
- int win_w = SCREEN_W < DisplayWidth(dpy, scr) ? SCREEN_W : DisplayWidth(dpy, scr);
- int win_h = SCREEN_H < DisplayHeight(dpy, scr) ? SCREEN_H : DisplayHeight(dpy, scr);
- Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr),
- 0, 0, win_w, win_h, 0,
- BlackPixel(dpy, scr),
- BlackPixel(dpy, scr));
- XStoreName(dpy, win, "textbench");
- XSelectInput(dpy, win, ExposureMask | KeyPressMask | StructureNotifyMask);
- Atom wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
- XSetWMProtocols(dpy, win, &wm_delete, 1);
- GC gc = XCreateGC(dpy, win, 0, NULL);
- XMapWindow(dpy, win);
- int running = 1;
- while (running) {
- XEvent ev;
- XNextEvent(dpy, &ev);
- switch (ev.type) {
- case Expose:
- if (ev.xexpose.count == 0)
- XShmPutImage(dpy, win, gc, img, 0, 0, 0, 0,
- win_w, win_h, False);
- break;
- case KeyPress: {
- KeySym ks = XLookupKeysym(&ev.xkey, 0);
- if (ks == XK_Escape || ks == XK_q)
- running = 0;
- break;
- }
- case ClientMessage:
- if ((Atom)ev.xclient.data.l[0] == wm_delete)
- running = 0;
- break;
- default:
- break;
- }
- }
- /* Cleanup. XDestroyImage would free img->data, which is shared memory,
- * so we skip it and let process exit release the X resources. */
- XFreeGC(dpy, gc);
- XDestroyWindow(dpy, win);
- XShmDetach(dpy, &shminfo);
- XSync(dpy, False);
- XCloseDisplay(dpy);
- shmdt(buf);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment