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

/* high precision time */
#ifdef WIN32
#include <windows.h>
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
#include <time.h>
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 <hiredis/hiredis.h>

#define N 10000

static void test(redisContext *cache)
{
    char key[10];
    int val;
    redisReply *reply;
    double t1, t2;
    int i;
    /* put speed */
    t1 = xtime();
    for(i = 0; i < N; i++)
    {
        sprintf(key, "K#%d", i + 1);
        val = i + 1;
        reply = redisCommand(cache, "SET %s %b", key, &val, sizeof(val));
        if (reply == NULL)
        {
            printf("set failed: %s\n", cache->errstr);
            exit(1);
        }
        freeReplyObject(reply);
    }
    t2 = xtime();
    printf("%d puts per second\n", (int)(N / (t2 - t1))); 
}

#define REP 5

int main()
{
    redisContext *cache;
    int i;
    cache = redisConnect("localhost", 6379);
    for(i = 0; i < REP; i++)
    {
        test(cache);
    }
    redisFree(cache);
    return 0;
}
