Skip to content

Instantly share code, notes, and snippets.

@joaomlneto
Created February 12, 2019 13:05
Show Gist options
  • Save joaomlneto/a595baca013335bdc8a9ef6800cda041 to your computer and use it in GitHub Desktop.
Save joaomlneto/a595baca013335bdc8a9ef6800cda041 to your computer and use it in GitHub Desktop.
mprotect benchmarks
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <unistd.h>
#include <sys/mman.h>
#define SIZE (1ull<<35) // 32GB
#define N (SIZE/sizeof(uint64_t))
#define NTIMES 100
void initialize(uint64_t *a, size_t size) {
printf("initializing... ");
fflush(stdout);
clock_t start = clock();
a[0] = 123;
for (size_t i=1; i < size; i++) {
a[i] = a[i-1] * a[i-1] % 100000;
}
clock_t end = clock();
double seconds = (double)(end - start) / CLOCKS_PER_SEC;
printf("done in %lf seconds\n", seconds);
}
void time_mprotect(void *addr, size_t size, size_t ntimes) {
clock_t start = clock();
for (size_t i=0; i < ntimes; i++) {
if (mprotect(addr, size, PROT_READ) == -1) {
perror("mprotect failed");
exit(-1);
}
if (mprotect(addr, size, PROT_READ | PROT_WRITE) == -1) {
perror("mprotect failed");
exit(-1);
}
}
clock_t end = clock();
double seconds = (double)(end - start) / CLOCKS_PER_SEC;
printf("mprotect %zuKB -> %lf seconds\n", size/1024, seconds/ntimes);
}
int main() {
uint64_t *a = mmap(NULL, N * sizeof(uint64_t), PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
long pagesize = sysconf(_SC_PAGESIZE);
initialize(a, N);
for(uint64_t i = pagesize; i <= SIZE; i *= 2) {
time_mprotect(a, i, NTIMES);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment