From deeaf5134dcd156500436ad57ba3d6e814a21849 Mon Sep 17 00:00:00 2001 From: batleram Date: Sat, 24 Oct 2026 17:28:26 -0400 Subject: Hardcode templating ~800ms --- .gitignore | 1 + Makefile | 7 +++---- calc.c | 59 ++++++++++++++++++++++++++++++++++++++++++----------------- calc.h | 3 +++ itoa_gen.py | 15 +++++++++++++++ 5 files changed, 64 insertions(+), 21 deletions(-) create mode 100644 itoa_gen.py diff --git a/.gitignore b/.gitignore index d629681..b932cae 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.json calc +itoa_lut.h diff --git a/Makefile b/Makefile index 75b6c76..7d75e27 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,12 @@ .PHONY: build -build: calc.c +build: calc.c lut clang -o calc -O3 -ggdb ./calc.c bench: build ./calc 10.0.0.0/8 2 -bench2: build - ./calc 10.0.0.0/6 2 - +lut: itoa_gen.py + python3 ./itoa_gen.py diff --git a/calc.c b/calc.c index 2f533b1..ddcfe95 100644 --- a/calc.c +++ b/calc.c @@ -1,4 +1,5 @@ #include "calc.h" +#include "itoa_lut.h" #include #include #include @@ -27,6 +28,25 @@ uint32_t subnetmask_for_netspace(unsigned int desired_netspace) { return start; } +void write_ip(char **chunk_ptr, uint32_t ip) { + // local ptr so we don't have to deref every time + char *ptr = *chunk_ptr; + LutEntry e = {.bits = itoa_lut[(ip >> 24) & 0xff]}; + WRITE_STR(ptr, e.fields.chars, e.fields.len) + ptr[0] = '.'; + ptr += 1; + e.bits = itoa_lut[(ip >> 16) & 0xff]; + WRITE_STR(ptr, e.fields.chars, e.fields.len) + ptr[0] = '.'; + ptr += 1; + e.bits = itoa_lut[(ip >> 8) & 0xff]; + WRITE_STR(ptr, e.fields.chars, e.fields.len) + ptr[0] = '.'; + ptr += 1; + e.bits = itoa_lut[ip & 0xff]; + WRITE_STR(ptr, e.fields.chars, e.fields.len) + *chunk_ptr = ptr; +} int main(int argc, char** argv) { struct timespec start; @@ -64,31 +84,36 @@ int main(int argc, char** argv) { fprintf(out, "[\n"); // file start uint32_t offset = 0; int i = 0; + char chunk[1024] = {0}; while (i>24 & 0xff),(i>>16 & 0xff),(i>>8 & 0xff),(i & 0xff) +#define WRITE_STR(ptr, str, len) for (int i=0; i\n") + f.write("typedef union { struct { char chars[3]; uint8_t len; } fields; uint32_t bits; } LutEntry;\n") + f.write("const uint32_t itoa_lut[256] = {") + out = [] + for i in range(0, 256): + running=len(str(i)) + for j in reversed(range(3)): + running = running << 8 + if j < len(str(i)): + running += ord(str(i)[j]) + out.append(hex(running)) + f.write(", ".join(out)) + f.write("};") + -- cgit v1.2.3