Skip to content

Instantly share code, notes, and snippets.

@ayende
Created December 29, 2024 09:31
Show Gist options
  • Save ayende/bb6f104e0d1f4df5d9b4a2cf3049a48c to your computer and use it in GitHub Desktop.
Save ayende/bb6f104e0d1f4df5d9b4a2cf3049a48c to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#define NUM_THREADS 128
#define WRITE_COUNT (16*1024)
#define BUFFER_SIZE (8*1024)
typedef struct {
int thread_id;
} ThreadData;
void *thread_func(void *arg) {
ThreadData *data = (ThreadData *)arg;
char filename[20];
snprintf(filename, sizeof(filename), "file_%d", data->thread_id);
int fd = open(filename, O_WRONLY | O_CREAT | O_SYNC | O_DIRECT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("open");
return NULL;
}
void *buffer = aligned_alloc(4096, BUFFER_SIZE); // Ensure alignment for O_DIRECT
if (!buffer) {
perror("aligned_alloc");
close(fd);
return NULL;
}
for (int i = 0; i < WRITE_COUNT; i++) {
ssize_t written = write(fd, buffer, BUFFER_SIZE);
if (written != (ssize_t)BUFFER_SIZE) {
perror("write");
break;
}
}
free(buffer);
close(fd);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
ThreadData thread_data[NUM_THREADS];
struct timeval start, end;
gettimeofday(&start, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
thread_data[i].thread_id = i;
if (pthread_create(&threads[i], NULL, thread_func, &thread_data[i])) {
fprintf(stderr, "Error creating thread %d\n", i);
exit(1);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
gettimeofday(&end, NULL);
double time_taken = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) * 1e-6;
printf("Time taken: %.2f seconds\n", time_taken);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment