Guest User

Text rendering benchmark

a guest
Nov 22nd, 2026
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 11.01 KB | Cryptocurrency | 0 0
  1. /*
  2.  * textbench.c - text rendering speed prototype
  3.  *
  4.  * AI-generated, human-reviewed and edited.
  5.  *
  6.  * Renders a grid of ASCII characters into a 3840x2160 32-bit buffer that lives in SysV shared memory.
  7.  * Renders 15 times, ignores the first 5, reports timing to stderr, then
  8.  * shows the buffer in an X window via MIT-SHM.
  9.  *
  10.  * Debian dependencies: sudo apt install build-essential pkg-config libfreetype-dev libx11-dev libxext-dev fonts-dejavu-core
  11.  *
  12.  * Build:
  13.  *   gcc -O2 -Wall -o textbench textbench.c $(pkg-config --cflags --libs freetype2) -lX11 -lXext
  14.  *
  15.  * You may use -O3 -march=native for better performance.
  16.  *
  17.  * Run:
  18.  *   ./textbench [path/to/font.ttf]
  19.  */
  20.  
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <time.h>
  26.  
  27. #include <sys/ipc.h>
  28. #include <sys/shm.h>
  29.  
  30. #include <X11/Xlib.h>
  31. #include <X11/Xutil.h>
  32. #include <X11/extensions/XShm.h>
  33.  
  34. #include <ft2build.h>
  35. #include FT_FREETYPE_H
  36.  
  37. /* ---------- Geometry ---------- */
  38. #define SCREEN_W      3840
  39. #define SCREEN_H      2160
  40. #define CELL_W        13          /* glyph box width  */
  41. #define CELL_H        24          /* glyph box height */
  42. #define LINE_H        24          /* distance between text lines */
  43. #define COLS          (SCREEN_W / CELL_W)   /* 240 */
  44. #define ROWS          (SCREEN_H / LINE_H)   /* 108 */
  45. #define BUF_PIXELS    ((size_t)SCREEN_W * SCREEN_H)
  46. #define BUF_BYTES     (BUF_PIXELS * sizeof(uint32_t))
  47.  
  48. /* ---------- Text / font ---------- */
  49. #define FIRST_CHAR    32          /* ' ' */
  50. #define LAST_CHAR     126         /* '~' */
  51. #define NUM_CHARS     (LAST_CHAR - FIRST_CHAR + 1)
  52. #define FONT_PIXEL_SIZE 20
  53.  
  54. /* ---------- Colours (0x00RRGGBB) ---------- */
  55. #define FG_COLOR      0x00FFFFFFu
  56. #define BG_COLOR      0x00000000u
  57.  
  58. /* ---------- Benchmark ---------- */
  59. #define WARMUP_RUNS   5
  60. #define MEASURED_RUNS 10
  61.  
  62. static const char *font_candidates[] = {
  63.     "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
  64.     "/usr/share/fonts/TTF/DejaVuSansMono.ttf",
  65.     "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
  66.     NULL
  67. };
  68.  
  69. /* Glyph cache: 8-bit coverage (alpha) per pixel of each 16x16 cell. */
  70. static uint8_t glyph_cache[NUM_CHARS][CELL_H][CELL_W];
  71.  
  72. /* Fixed-size 2D text grid. */
  73. static unsigned char text[ROWS][COLS];
  74.  
  75. static void die(const char *msg)
  76. {
  77.     fprintf(stderr, "error: %s\n", msg);
  78.     exit(EXIT_FAILURE);
  79. }
  80.  
  81. static const char *find_font(void)
  82. {
  83.     for (int i = 0; font_candidates[i]; i++) {
  84.         FILE *f = fopen(font_candidates[i], "rb");
  85.         if (f) {
  86.             fclose(f);
  87.             return font_candidates[i];
  88.         }
  89.     }
  90.     return NULL;
  91. }
  92.  
  93. /* Rasterize all printable ASCII characters into the 16x16 glyph cache. */
  94. static void build_glyph_cache(const char *fontpath)
  95. {
  96.     FT_Library lib;
  97.     FT_Face face;
  98.  
  99.     if (FT_Init_FreeType(&lib))
  100.         die("FT_Init_FreeType failed");
  101.     if (FT_New_Face(lib, fontpath, 0, &face))
  102.         die("could not load font file (pass one as argument)");
  103.     if (FT_Set_Pixel_Sizes(face, 0, FONT_PIXEL_SIZE))
  104.         die("FT_Set_Pixel_Sizes failed");
  105.  
  106.     /* Baseline position inside the 16 px cell, in whole pixels. */
  107.     const int baseline = (int)(face->size->metrics.ascender >> 6);
  108.  
  109.     for (int c = FIRST_CHAR; c <= LAST_CHAR; c++) {
  110.         uint8_t (*cell)[CELL_W] = glyph_cache[c - FIRST_CHAR];
  111.         memset(cell, 0, CELL_W * CELL_H);
  112.  
  113.         if (FT_Load_Char(face, c, FT_LOAD_RENDER))
  114.             continue;
  115.  
  116.         const FT_Bitmap *bm = &face->glyph->bitmap;
  117.         const int ox = face->glyph->bitmap_left;
  118.         const int oy = baseline - face->glyph->bitmap_top;
  119.  
  120.         for (unsigned int y = 0; y < bm->rows; y++) {
  121.             int dy = oy + (int)y;
  122.             if (dy < 0 || dy >= CELL_H)
  123.                 continue;
  124.             for (unsigned int x = 0; x < bm->width; x++) {
  125.                 int dx = ox + (int)x;
  126.                 if (dx < 0 || dx >= CELL_W)
  127.                     continue;
  128.                 cell[dy][dx] = bm->buffer[y * bm->pitch + x];
  129.             }
  130.         }
  131.     }
  132.  
  133.     FT_Done_Face(face);
  134.     FT_Done_FreeType(lib);
  135. }
  136.  
  137. /* Fill the text grid with printable ASCII in order, wrapping around. */
  138. static void generate_text(void)
  139. {
  140.     for (int r = 0; r < ROWS; r++)
  141.         for (int c = 0; c < COLS; c++)
  142.             text[r][c] = (unsigned char)(FIRST_CHAR + ((size_t)r * COLS + c) % NUM_CHARS);
  143. }
  144.  
  145. /* Alpha-blend src over dst, per channel. */
  146. static inline uint32_t blend(uint32_t dst, uint32_t src, uint8_t a)
  147. {
  148.     const uint32_t ia = 255u - a;
  149.     const uint32_t r = ((src >> 16 & 0xFF) * a + (dst >> 16 & 0xFF) * ia) / 255u;
  150.     const uint32_t g = ((src >>  8 & 0xFF) * a + (dst >>  8 & 0xFF) * ia) / 255u;
  151.     const uint32_t b = ((src       & 0xFF) * a + (dst       & 0xFF) * ia) / 255u;
  152.     return (r << 16) | (g << 8) | b;
  153. }
  154.  
  155.  
  156. /* Render the whole text grid into the framebuffer. Every cell is blended
  157.  * (no early-out on zero alpha) so the cost per letter is constant. */
  158. static void render_text(uint32_t *buf)
  159. {
  160.     for (size_t i = 0; i < BUF_PIXELS; i++) {
  161.         buf[i] = BG_COLOR;
  162.     }
  163.  
  164.     for (int row = 0; row < ROWS; row++) {
  165.         for (int col = 0; col < COLS; col++) {
  166.             const int idx = text[row][col] - FIRST_CHAR;
  167.             const int x0 = col * CELL_W;
  168.             const int y0 = row * LINE_H;
  169.  
  170.             for (int y = 0; y < CELL_H; y++) {
  171.                 uint32_t *dst = buf + (size_t)(y0 + y) * SCREEN_W + x0;
  172.                 const uint8_t *src = glyph_cache[idx][y];
  173.                 for (int x = 0; x < CELL_W; x++)
  174.                     dst[x] = blend(/* dst[x] */BG_COLOR, FG_COLOR, src[x]);
  175.             }
  176.         }
  177.     }
  178. }
  179.  
  180. static double elapsed_ns(const struct timespec *a, const struct timespec *b)
  181. {
  182.     return (double)(b->tv_sec - a->tv_sec) * 1e9 + (double)(b->tv_nsec - a->tv_nsec);
  183. }
  184.  
  185. static void run_benchmark(uint32_t *buf)
  186. {
  187.     const long long letters_per_frame = (long long)COLS * ROWS;
  188.     const long long pixels_per_frame  = (long long)BUF_PIXELS;
  189.     double total_ns = 0.0;
  190.  
  191.     for (int run = 0; run < WARMUP_RUNS + MEASURED_RUNS; run++) {
  192.         struct timespec t0, t1;
  193.         clock_gettime(CLOCK_MONOTONIC, &t0);
  194.         render_text(buf);
  195.         clock_gettime(CLOCK_MONOTONIC, &t1);
  196.  
  197.         if (run >= WARMUP_RUNS) {
  198.             total_ns += elapsed_ns(&t0, &t1);
  199.         }
  200.     }
  201.  
  202.     const double total_s        = total_ns / 1e9;
  203.     const double total_letters  = (double)letters_per_frame * MEASURED_RUNS;
  204.     const double total_pixels   = (double)pixels_per_frame * MEASURED_RUNS;
  205.  
  206.     fprintf(stderr, "\n=== Text rendering benchmark ===\n");
  207.     fprintf(stderr, "Buffer:            %d x %d px (%zu bytes)\n",
  208.             SCREEN_W, SCREEN_H, BUF_BYTES);
  209.     fprintf(stderr, "Grid:              %d cols x %d rows = %lld letters/frame\n",
  210.             COLS, ROWS, letters_per_frame);
  211.     fprintf(stderr, "Measured runs:     %d (first %d ignored)\n",
  212.             MEASURED_RUNS, WARMUP_RUNS);
  213.     fprintf(stderr, "Total time:        %.3f ms\n", total_ns / 1e6);
  214.     fprintf(stderr, "Avg per frame:     %.3f ms\n",
  215.             total_ns / 1e6 / MEASURED_RUNS);
  216.     fprintf(stderr, "Time per letter:   %.1f ns\n", total_ns / total_letters);
  217.     fprintf(stderr, "Letters/second:    %.0f\n", total_letters / total_s);
  218.     fprintf(stderr, "Pixels/second:     %.3f Mpx/s\n",
  219.             total_pixels / total_s / 1e6);
  220.     fprintf(stderr, "Note: pixels are full buffer pixels (background clear\n      included); letters are grid cells incl. spaces.\n\n");
  221. }
  222.  
  223. int main(int argc, char **argv)
  224. {
  225.     const char *font = (argc > 1) ? argv[1] : find_font();
  226.     if (!font)
  227.         die("no font found; pass a .ttf path as the first argument");
  228.  
  229.     /* Allocate the frame buffer in SysV shared memory from the start. */
  230.     int shmid = shmget(IPC_PRIVATE, BUF_BYTES, IPC_CREAT | 0600);
  231.     if (shmid < 0)
  232.         die("shmget failed");
  233.  
  234.     uint32_t *buf = shmat(shmid, NULL, 0);
  235.     if (buf == (void *)-1)
  236.         die("shmat failed");
  237.  
  238.     build_glyph_cache(font);
  239.     generate_text();
  240.     run_benchmark(buf);
  241.  
  242.     /* ---------- X11 display via MIT-SHM ---------- */
  243.     Display *dpy = XOpenDisplay(NULL);
  244.     if (!dpy)
  245.         die("cannot open X display");
  246.     if (!XShmQueryExtension(dpy))
  247.         die("X server does not support MIT-SHM");
  248.  
  249.     int scr = DefaultScreen(dpy);
  250.     int depth = DefaultDepth(dpy, scr);
  251.     if (depth != 24)
  252.         die("this prototype expects a 24-bit default visual");
  253.  
  254.     XShmSegmentInfo shminfo;
  255.     memset(&shminfo, 0, sizeof(shminfo));
  256.     shminfo.shmid    = shmid;
  257.     shminfo.shmaddr  = (char *)buf;
  258.     shminfo.readOnly = False;
  259.  
  260.     XImage *img = XShmCreateImage(dpy, DefaultVisual(dpy, scr), depth,
  261.                                   ZPixmap, NULL, &shminfo,
  262.                                   SCREEN_W, SCREEN_H);
  263.     if (!img)
  264.         die("XShmCreateImage failed");
  265.     if (img->bits_per_pixel != 32)
  266.         die("expected 32 bits per pixel XImage");
  267.  
  268.     img->data = (char *)buf;   /* point the XImage at our shared buffer */
  269.  
  270.     if (!XShmAttach(dpy, &shminfo))
  271.         die("XShmAttach failed");
  272.     XSync(dpy, False);
  273.     /* Segment is destroyed once everyone detaches; ensures cleanup. */
  274.     shmctl(shmid, IPC_RMID, NULL);
  275.  
  276.     /* Clamp window to the display so it stays visible. */
  277.     int win_w = SCREEN_W < DisplayWidth(dpy, scr)  ? SCREEN_W : DisplayWidth(dpy, scr);
  278.     int win_h = SCREEN_H < DisplayHeight(dpy, scr) ? SCREEN_H : DisplayHeight(dpy, scr);
  279.  
  280.     Window win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr),
  281.                                      0, 0, win_w, win_h, 0,
  282.                                      BlackPixel(dpy, scr),
  283.                                      BlackPixel(dpy, scr));
  284.     XStoreName(dpy, win, "textbench");
  285.     XSelectInput(dpy, win, ExposureMask | KeyPressMask | StructureNotifyMask);
  286.  
  287.     Atom wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
  288.     XSetWMProtocols(dpy, win, &wm_delete, 1);
  289.  
  290.     GC gc = XCreateGC(dpy, win, 0, NULL);
  291.     XMapWindow(dpy, win);
  292.  
  293.     int running = 1;
  294.     while (running) {
  295.         XEvent ev;
  296.         XNextEvent(dpy, &ev);
  297.         switch (ev.type) {
  298.         case Expose:
  299.             if (ev.xexpose.count == 0)
  300.                 XShmPutImage(dpy, win, gc, img, 0, 0, 0, 0,
  301.                              win_w, win_h, False);
  302.             break;
  303.         case KeyPress: {
  304.             KeySym ks = XLookupKeysym(&ev.xkey, 0);
  305.             if (ks == XK_Escape || ks == XK_q)
  306.                 running = 0;
  307.             break;
  308.         }
  309.         case ClientMessage:
  310.             if ((Atom)ev.xclient.data.l[0] == wm_delete)
  311.                 running = 0;
  312.             break;
  313.         default:
  314.             break;
  315.         }
  316.     }
  317.  
  318.     /* Cleanup. XDestroyImage would free img->data, which is shared memory,
  319.      * so we skip it and let process exit release the X resources. */
  320.     XFreeGC(dpy, gc);
  321.     XDestroyWindow(dpy, win);
  322.     XShmDetach(dpy, &shminfo);
  323.     XSync(dpy, False);
  324.     XCloseDisplay(dpy);
  325.     shmdt(buf);
  326.     return EXIT_SUCCESS;
  327. }
  328.  
Advertisement
Add Comment
Please, Sign In to add comment