Skip to content

Instantly share code, notes, and snippets.

@yuryu
Created August 22, 2013 10:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuryu/6305572 to your computer and use it in GitHub Desktop.
Save yuryu/6305572 to your computer and use it in GitHub Desktop.
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