Skip to content

Instantly share code, notes, and snippets.

@FauxFaux
Created July 12, 2017 16:41
Show Gist options
  • Save FauxFaux/a47d2fcb9472b1b4950ddcc8b03d4746 to your computer and use it in GitHub Desktop.
Save FauxFaux/a47d2fcb9472b1b4950ddcc8b03d4746 to your computer and use it in GitHub Desktop.
Is hand-written C faster than Python? Yes, yes it is.
// make CFLAGS=-O2 dpkgs && time ./dpkgs /lib/systemd/systemd
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv) {
const char *needle = argv[1];
const size_t needle_len = strlen(needle);
const size_t buf_len = needle_len + 2;
char *buf = malloc(needle_len + 3);
sprintf(buf, "\n%s\n", needle);
int dir = open("/var/lib/dpkg/info", O_DIRECTORY);
assert(dir);
DIR *open_dir = fdopendir(dir);
assert(dir);
for (struct dirent *ent = readdir(open_dir); ent; ent = readdir(open_dir)) {
const size_t len = strlen(ent->d_name);
if (len < 5 || strcmp(ent->d_name + len - 5, ".list")) {
continue;
}
int file = openat(dir, ent->d_name, O_RDONLY);
assert(file);
struct stat stat;
int stat_status = fstat(file, &stat);
assert(!stat_status);
char *map = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, file, 0);
assert(map);
if (memmem(map, stat.st_size, buf, buf_len)) {
printf("%s\n", ent->d_name);
}
munmap(map, stat.st_size);
close(file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment