Skip to content

Instantly share code, notes, and snippets.

@callowaysutton
Created September 25, 2024 04:50
Show Gist options
  • Save callowaysutton/377aacd2d108131a45c00c9d874cc733 to your computer and use it in GitHub Desktop.
Save callowaysutton/377aacd2d108131a45c00c9d874cc733 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#define NUM_ITERATIONS 10000
// Function to remove lines starting with '!'
void remove_internal_headers(char *header, size_t len) {
char *read_ptr = header;
char *write_ptr = header;
while (read_ptr < header + len) {
// Find the start and end of the next line (\r\n)
char *line_end = strstr(read_ptr, "\r\n");
if (!line_end) {
break; // If no more newlines, break
}
line_end += 2; // Move past \r\n
// Check if the line starts with '!'
if (*read_ptr == '!') {
// Skip this line, don't copy it
read_ptr = line_end;
} else {
// Copy the line
size_t line_length = line_end - read_ptr;
if (read_ptr != write_ptr) {
memmove(write_ptr, read_ptr, line_length);
}
write_ptr += line_length;
read_ptr = line_end;
}
}
// Null-terminate the new header after write_ptr
*write_ptr = '\0';
}
// Benchmark function
void benchmark(size_t size) {
// Allocate a buffer with random data
char *header = malloc(size + 1);
// Fill buffer with lines, 50% of which start with '!'
for (size_t i = 0; i < size; i += 20) {
if (i % 2 == 0) {
snprintf(header + i, 20, "header%d: value\r\n", i / 20);
} else {
snprintf(header + i, 20, "!header%d: secret\r\n", i / 20);
}
}
header[size] = '\0';
long total_ns = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
// Measure time
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
remove_internal_headers(header, size);
clock_gettime(CLOCK_MONOTONIC, &end);
// Calculate elapsed time in nanoseconds
long seconds = end.tv_sec - start.tv_sec;
long ns = end.tv_nsec - start.tv_nsec;
if (end.tv_nsec < start.tv_nsec) {
seconds--;
ns += 1000000000;
}
total_ns += seconds * 1000000000L + ns;
}
// Calculate and print average time in nanoseconds
long avg_ns = total_ns / NUM_ITERATIONS;
printf("Size: %zu bytes, Average Time: %ld ns\n", size, avg_ns);
free(header);
}
int main() {
// Run benchmarks for sizes from 512 bytes to 1MB
size_t sizes[] = {512, 1024, 4096, 16384, 65536, 262144, 1048576};
for (int i = 0; i < 7; i++) {
benchmark(sizes[i]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment