/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <time.h>

#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

/* high precision time */
#ifdef WIN32
static inline double xtime()
{
    BOOL res;
    LARGE_INTEGER t, f;
    QueryPerformanceFrequency(&f);
    res = QueryPerformanceCounter(&t);
    return res ? (t.QuadPart * 1.0 / f.QuadPart) : 0;
}
#else
static inline double xtime()
{
    int res;
    struct timespec t;
    res = clock_gettime(CLOCK_MONOTONIC, &t);
    return (res == 0) ? (t.tv_sec + t.tv_nsec / 1000000000.0) : 0;
}
#endif

#include <libmemcached/memcached.h>

#define N 10000

static void test(memcached_st *cache)
{
    char key[10];
    int val;
    memcached_return_t stat;
    double t1, t2;
    int i;
    /* put speed */
    t1 = xtime();
    for(i = 0; i < N; i++)
    {
        sprintf(key, "K#%d", i + 1);
        val = i + 1;
        stat = memcached_set(cache, key, strlen(key), (char *)&val, sizeof(val), 0, 0);
        if (stat != MEMCACHED_SUCCESS)
        {
            printf("set failed: %s\n", memcached_error(cache));
            exit(1);
        }
    }
    t2 = xtime();
    printf("%d puts per second\n", (int)(N / (t2 - t1))); 
}

#define REP 5

int main()
{
    const char *cfg = "--SERVER=localhost --BINARY-PROTOCOL";
    memcached_st *cache;
    int i;
#ifdef WIN32
    WSADATA WSAData;
    WSAStartup(0x0101, &WSAData);
#endif
    cache = memcached(cfg, strlen(cfg));
    for(i = 0; i < REP; i++)
    {
        test(cache);
    }
    memcached_free(cache);
#ifdef WIN32
    WSACleanup();
#endif
     return 0;
}
