Linux kernel quiz: Why is this program so slow and takes around 50ms to run?
What line do you have to add to make it run in ~3ms instead without interfering with what this program does?
#include <pthread.h>
#include <unistd.h>
#include <err.h>
#include <sys/socket.h>
static void open_sockets(void) {
for (int i=0; i<256; i++) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
err(1, "socket");
}
}
static void *thread_fn(void *dummy) {
open_sockets();
return NULL;
}
int main(void) {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_fn, NULL))
errx(1, "pthread_create");
open_sockets();
if (pthread_join(thread, NULL))
errx(1, "pthread_join");
return 0;
}
user@debian12:~/test$ gcc -O2 -o slow slow.c -Wall
user@debian12:~/test$ time ./slow
real 0m0.041s
user 0m0.003s
sys 0m0.000s
user@debian12:~/test$ time ./slow
real 0m0.053s
user 0m0.003s
sys 0m0.000s
user@debian12:~/test$