Skip to content

Instantly share code, notes, and snippets.

@yuryu yuryu/hostsbench.c
Created Aug 22, 2013

Embed
What would you like to do?
name lookup benchmark
#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <memory.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
int resolv_once(const char *host)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
struct addrinfo *result;
int s = getaddrinfo(host, NULL, &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
freeaddrinfo(result);
return 0;
}
int main(int argc, char *argv[])
{
if (argc <= 2) {
fputs("usage: hostsbench [count] [host]\n", stderr);
return 1;
}
int count = atoi(argv[1]);
const char *host = argv[2];
struct timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
for (int i = 0; i < count; ++i) {
resolv_once(host);
}
clock_gettime(CLOCK_REALTIME, &end);
if (start.tv_nsec > end.tv_nsec) {
end.tv_sec--;
end.tv_nsec += 1000000000;
}
double elapsed = (double)(end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("Resolved %d times. Elapsed time = %.3f seconds, %.3f us per host.\n",
count, elapsed, elapsed * 1000 / count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.