]> git.saurik.com Git - redis.git/blob - src/redis-benchmark.c
Find substrings to randomize when the client is created
[redis.git] / src / redis-benchmark.c
1 /* Redis benchmark utility.
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "fmacros.h"
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <sys/time.h>
39 #include <signal.h>
40 #include <assert.h>
41
42 #include "ae.h"
43 #include "hiredis.h"
44 #include "sds.h"
45 #include "adlist.h"
46 #include "zmalloc.h"
47
48 #define CLIENT_CONNECTING 0
49 #define CLIENT_SENDQUERY 1
50 #define CLIENT_READREPLY 2
51
52 #define REDIS_NOTUSED(V) ((void) V)
53
54 static struct config {
55 int debug;
56 int numclients;
57 int requests;
58 int liveclients;
59 int donerequests;
60 int keysize;
61 int datasize;
62 int randomkeys;
63 int randomkeys_keyspacelen;
64 aeEventLoop *el;
65 char *hostip;
66 int hostport;
67 char *hostsocket;
68 int keepalive;
69 long long start;
70 long long totlatency;
71 long long *latency;
72 char *title;
73 list *clients;
74 int quiet;
75 int loop;
76 int idlemode;
77 } config;
78
79 typedef struct _client {
80 redisContext *context;
81 int state;
82 sds obuf;
83 char *randptr[10]; /* needed for MSET against 10 keys */
84 size_t randlen;
85 unsigned int written; /* bytes of 'obuf' already written */
86 long long start; /* start time of a request */
87 long long latency; /* request latency */
88 } *client;
89
90 /* Prototypes */
91 static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask);
92 static void createMissingClients(client c);
93
94 /* Implementation */
95 static long long ustime(void) {
96 struct timeval tv;
97 long long ust;
98
99 gettimeofday(&tv, NULL);
100 ust = ((long)tv.tv_sec)*1000000;
101 ust += tv.tv_usec;
102 return ust;
103 }
104
105 static long long mstime(void) {
106 struct timeval tv;
107 long long mst;
108
109 gettimeofday(&tv, NULL);
110 mst = ((long)tv.tv_sec)*1000;
111 mst += tv.tv_usec/1000;
112 return mst;
113 }
114
115 static void freeClient(client c) {
116 listNode *ln;
117 aeDeleteFileEvent(config.el,c->context->fd,AE_WRITABLE);
118 aeDeleteFileEvent(config.el,c->context->fd,AE_READABLE);
119 redisFree(c->context);
120 sdsfree(c->obuf);
121 zfree(c);
122 config.liveclients--;
123 ln = listSearchKey(config.clients,c);
124 assert(ln != NULL);
125 listDelNode(config.clients,ln);
126 }
127
128 static void freeAllClients(void) {
129 listNode *ln = config.clients->head, *next;
130
131 while(ln) {
132 next = ln->next;
133 freeClient(ln->value);
134 ln = next;
135 }
136 }
137
138 static void resetClient(client c) {
139 aeDeleteFileEvent(config.el,c->context->fd,AE_WRITABLE);
140 aeDeleteFileEvent(config.el,c->context->fd,AE_READABLE);
141 aeCreateFileEvent(config.el,c->context->fd,AE_WRITABLE,writeHandler,c);
142 c->written = 0;
143 c->state = CLIENT_SENDQUERY;
144 c->start = ustime();
145 c->latency = -1;
146 }
147
148 static void randomizeClientKey(client c) {
149 char buf[32];
150 size_t i, r;
151
152 for (i = 0; i < c->randlen; i++) {
153 r = random() % config.randomkeys_keyspacelen;
154 snprintf(buf,sizeof(buf),"%012lu",r);
155 memcpy(c->randptr[i],buf,12);
156 }
157 }
158
159 static void clientDone(client c) {
160 if (config.donerequests == config.requests) {
161 freeClient(c);
162 aeStop(config.el);
163 return;
164 }
165 if (config.keepalive) {
166 resetClient(c);
167 if (config.randomkeys) randomizeClientKey(c);
168 } else {
169 config.liveclients--;
170 createMissingClients(c);
171 config.liveclients++;
172 freeClient(c);
173 }
174 }
175
176 static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
177 client c = privdata;
178 void *reply = NULL;
179 REDIS_NOTUSED(el);
180 REDIS_NOTUSED(fd);
181 REDIS_NOTUSED(mask);
182
183 /* Calculate latency only for the first read event. This means that the
184 * server already sent the reply and we need to parse it. Parsing overhead
185 * is not part of the latency, so calculate it only once, here. */
186 if (c->latency < 0) c->latency = ustime()-(c->start);
187
188 if (redisBufferRead(c->context) != REDIS_OK) {
189 fprintf(stderr,"Error: %s\n",c->context->errstr);
190 exit(1);
191 } else {
192 if (redisGetReply(c->context,&reply) != REDIS_OK) {
193 fprintf(stderr,"Error: %s\n",c->context->errstr);
194 exit(1);
195 }
196 if (reply != NULL) {
197 if (reply == (void*)REDIS_REPLY_ERROR) {
198 fprintf(stderr,"Unexpected error reply, exiting...\n");
199 exit(1);
200 }
201
202 if (config.donerequests < config.requests)
203 config.latency[config.donerequests++] = c->latency;
204 clientDone(c);
205 }
206 }
207 }
208
209 static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
210 client c = privdata;
211 REDIS_NOTUSED(el);
212 REDIS_NOTUSED(fd);
213 REDIS_NOTUSED(mask);
214
215 if (c->state == CLIENT_CONNECTING) {
216 c->state = CLIENT_SENDQUERY;
217 c->start = ustime();
218 c->latency = -1;
219 }
220 if (sdslen(c->obuf) > c->written) {
221 void *ptr = c->obuf+c->written;
222 int nwritten = write(c->context->fd,ptr,sdslen(c->obuf)-c->written);
223 if (nwritten == -1) {
224 if (errno != EPIPE)
225 fprintf(stderr, "Writing to socket: %s\n", strerror(errno));
226 freeClient(c);
227 return;
228 }
229 c->written += nwritten;
230 if (sdslen(c->obuf) == c->written) {
231 aeDeleteFileEvent(config.el,c->context->fd,AE_WRITABLE);
232 aeCreateFileEvent(config.el,c->context->fd,AE_READABLE,readHandler,c);
233 c->state = CLIENT_READREPLY;
234 }
235 }
236 }
237
238 static client createClient(char *cmd, int len) {
239 client c = zmalloc(sizeof(struct _client));
240 if (config.hostsocket == NULL) {
241 c->context = redisConnectNonBlock(config.hostip,config.hostport);
242 } else {
243 c->context = redisConnectUnixNonBlock(config.hostsocket);
244 }
245 if (c->context->err) {
246 fprintf(stderr,"Could not connect to Redis at ");
247 if (config.hostsocket == NULL)
248 fprintf(stderr,"%s:%d: %s\n",config.hostip,config.hostport,c->context->errstr);
249 else
250 fprintf(stderr,"%s: %s\n",config.hostsocket,c->context->errstr);
251 exit(1);
252 }
253 c->state = CLIENT_CONNECTING;
254 c->obuf = sdsnewlen(cmd,len);
255 c->randlen = 0;
256 c->written = 0;
257
258 /* Find substrings in the output buffer that need to be randomized. */
259 if (config.randomkeys) {
260 char *p = c->obuf, *newline;
261 while ((p = strstr(p,":rand:")) != NULL) {
262 newline = strstr(p,"\r\n");
263 assert(newline-(p+6) == 12); /* 12 chars for randomness */
264 assert(c->randlen < (signed)(sizeof(c->randptr)/sizeof(char*)));
265 c->randptr[c->randlen++] = p+6;
266 p = newline+2;
267 }
268 }
269
270 redisSetReplyObjectFunctions(c->context,NULL);
271 aeCreateFileEvent(config.el,c->context->fd,AE_WRITABLE,writeHandler,c);
272 listAddNodeTail(config.clients,c);
273 config.liveclients++;
274 return c;
275 }
276
277 static void createMissingClients(client c) {
278 int n = 0;
279
280 while(config.liveclients < config.numclients) {
281 client new = createClient(c->obuf,sdslen(c->obuf));
282 if (config.randomkeys) randomizeClientKey(new);
283
284 /* Listen backlog is quite limited on most systems */
285 if (++n > 64) {
286 usleep(50000);
287 n = 0;
288 }
289 }
290 }
291
292 static int compareLatency(const void *a, const void *b) {
293 return (*(long long*)a)-(*(long long*)b);
294 }
295
296 static void showLatencyReport(void) {
297 int i, curlat = 0;
298 float perc, reqpersec;
299
300 reqpersec = (float)config.donerequests/((float)config.totlatency/1000);
301 if (!config.quiet) {
302 printf("====== %s ======\n", config.title);
303 printf(" %d requests completed in %.2f seconds\n", config.donerequests,
304 (float)config.totlatency/1000);
305 printf(" %d parallel clients\n", config.numclients);
306 printf(" %d bytes payload\n", config.datasize);
307 printf(" keep alive: %d\n", config.keepalive);
308 printf("\n");
309
310 qsort(config.latency,config.requests,sizeof(long long),compareLatency);
311 for (i = 0; i < config.requests; i++) {
312 if (config.latency[i]/1000 != curlat || i == (config.requests-1)) {
313 curlat = config.latency[i]/1000;
314 perc = ((float)(i+1)*100)/config.requests;
315 printf("%.2f%% <= %d milliseconds\n", perc, curlat);
316 }
317 }
318 printf("%.2f requests per second\n\n", reqpersec);
319 } else {
320 printf("%s: %.2f requests per second\n", config.title, reqpersec);
321 }
322 }
323
324 static void benchmark(char *title, char *cmd, int len) {
325 client c;
326
327 config.title = title;
328 config.donerequests = 0;
329
330 c = createClient(cmd,len);
331 createMissingClients(c);
332
333 config.start = mstime();
334 aeMain(config.el);
335 config.totlatency = mstime()-config.start;
336
337 showLatencyReport();
338 freeAllClients();
339 }
340
341 void parseOptions(int argc, char **argv) {
342 int i;
343
344 for (i = 1; i < argc; i++) {
345 int lastarg = i==argc-1;
346
347 if (!strcmp(argv[i],"-c") && !lastarg) {
348 config.numclients = atoi(argv[i+1]);
349 i++;
350 } else if (!strcmp(argv[i],"-n") && !lastarg) {
351 config.requests = atoi(argv[i+1]);
352 i++;
353 } else if (!strcmp(argv[i],"-k") && !lastarg) {
354 config.keepalive = atoi(argv[i+1]);
355 i++;
356 } else if (!strcmp(argv[i],"-h") && !lastarg) {
357 config.hostip = argv[i+1];
358 i++;
359 } else if (!strcmp(argv[i],"-p") && !lastarg) {
360 config.hostport = atoi(argv[i+1]);
361 i++;
362 } else if (!strcmp(argv[i],"-s") && !lastarg) {
363 config.hostsocket = argv[i+1];
364 i++;
365 } else if (!strcmp(argv[i],"-d") && !lastarg) {
366 config.datasize = atoi(argv[i+1]);
367 i++;
368 if (config.datasize < 1) config.datasize=1;
369 if (config.datasize > 1024*1024) config.datasize = 1024*1024;
370 } else if (!strcmp(argv[i],"-r") && !lastarg) {
371 config.randomkeys = 1;
372 config.randomkeys_keyspacelen = atoi(argv[i+1]);
373 if (config.randomkeys_keyspacelen < 0)
374 config.randomkeys_keyspacelen = 0;
375 i++;
376 } else if (!strcmp(argv[i],"-q")) {
377 config.quiet = 1;
378 } else if (!strcmp(argv[i],"-l")) {
379 config.loop = 1;
380 } else if (!strcmp(argv[i],"-D")) {
381 config.debug = 1;
382 } else if (!strcmp(argv[i],"-I")) {
383 config.idlemode = 1;
384 } else {
385 printf("Wrong option '%s' or option argument missing\n\n",argv[i]);
386 printf("Usage: redis-benchmark [-h <host>] [-p <port>] [-c <clients>] [-n <requests]> [-k <boolean>]\n\n");
387 printf(" -h <hostname> Server hostname (default 127.0.0.1)\n");
388 printf(" -p <port> Server port (default 6379)\n");
389 printf(" -s <socket> Server socket (overrides host and port)\n");
390 printf(" -c <clients> Number of parallel connections (default 50)\n");
391 printf(" -n <requests> Total number of requests (default 10000)\n");
392 printf(" -d <size> Data size of SET/GET value in bytes (default 2)\n");
393 printf(" -k <boolean> 1=keep alive 0=reconnect (default 1)\n");
394 printf(" -r <keyspacelen> Use random keys for SET/GET/INCR, random values for SADD\n");
395 printf(" Using this option the benchmark will get/set keys\n");
396 printf(" in the form mykey_rand000000012456 instead of constant\n");
397 printf(" keys, the <keyspacelen> argument determines the max\n");
398 printf(" number of values for the random number. For instance\n");
399 printf(" if set to 10 only rand000000000000 - rand000000000009\n");
400 printf(" range will be allowed.\n");
401 printf(" -q Quiet. Just show query/sec values\n");
402 printf(" -l Loop. Run the tests forever\n");
403 printf(" -I Idle mode. Just open N idle connections and wait.\n");
404 printf(" -D Debug mode. more verbose.\n");
405 exit(1);
406 }
407 }
408 }
409
410 int showThroughput(struct aeEventLoop *eventLoop, long long id, void *clientData) {
411 REDIS_NOTUSED(eventLoop);
412 REDIS_NOTUSED(id);
413 REDIS_NOTUSED(clientData);
414
415 float dt = (float)(mstime()-config.start)/1000.0;
416 float rps = (float)config.donerequests/dt;
417 printf("%s: %.2f\r", config.title, rps);
418 fflush(stdout);
419 return 250; /* every 250ms */
420 }
421
422 int main(int argc, char **argv) {
423 int i;
424 client c;
425
426 signal(SIGHUP, SIG_IGN);
427 signal(SIGPIPE, SIG_IGN);
428
429 config.debug = 0;
430 config.numclients = 50;
431 config.requests = 10000;
432 config.liveclients = 0;
433 config.el = aeCreateEventLoop();
434 aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL);
435 config.keepalive = 1;
436 config.donerequests = 0;
437 config.datasize = 3;
438 config.randomkeys = 0;
439 config.randomkeys_keyspacelen = 0;
440 config.quiet = 0;
441 config.loop = 0;
442 config.idlemode = 0;
443 config.latency = NULL;
444 config.clients = listCreate();
445 config.hostip = "127.0.0.1";
446 config.hostport = 6379;
447 config.hostsocket = NULL;
448
449 parseOptions(argc,argv);
450 config.latency = zmalloc(sizeof(long long)*config.requests);
451
452 if (config.keepalive == 0) {
453 printf("WARNING: keepalive disabled, you probably need 'echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse' for Linux and 'sudo sysctl -w net.inet.tcp.msl=1000' for Mac OS X in order to use a lot of clients/requests\n");
454 }
455
456 if (config.idlemode) {
457 printf("Creating %d idle connections and waiting forever (Ctrl+C when done)\n", config.numclients);
458 c = createClient("",0); /* will never receive a reply */
459 createMissingClients(c);
460 aeMain(config.el);
461 /* and will wait for every */
462 }
463
464 do {
465 char *data, *cmd;
466 int len;
467
468 data = zmalloc(config.datasize+1);
469 memset(data,'x',config.datasize);
470 data[config.datasize] = '\0';
471
472 benchmark("PING (inline)","PING\r\n",6);
473
474 len = redisFormatCommand(&cmd,"PING");
475 benchmark("PING",cmd,len);
476 free(cmd);
477
478 const char *argv[21];
479 argv[0] = "MSET";
480 for (i = 1; i < 21; i += 2) {
481 argv[i] = "foo:rand:000000000000";
482 argv[i+1] = data;
483 }
484 len = redisFormatCommandArgv(&cmd,21,argv,NULL);
485 benchmark("MSET (10 keys)",cmd,len);
486 free(cmd);
487
488 len = redisFormatCommand(&cmd,"SET foo:rand:000000000000 %s",data);
489 benchmark("SET",cmd,len);
490 free(cmd);
491
492 len = redisFormatCommand(&cmd,"GET foo:rand:000000000000");
493 benchmark("GET",cmd,len);
494 free(cmd);
495
496 len = redisFormatCommand(&cmd,"INCR counter:rand:000000000000");
497 benchmark("INCR",cmd,len);
498 free(cmd);
499
500 len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
501 benchmark("LPUSH",cmd,len);
502 free(cmd);
503
504 len = redisFormatCommand(&cmd,"LPOP mylist");
505 benchmark("LPOP",cmd,len);
506 free(cmd);
507
508 len = redisFormatCommand(&cmd,"SADD myset counter:rand:000000000000");
509 benchmark("SADD",cmd,len);
510 free(cmd);
511
512 len = redisFormatCommand(&cmd,"SPOP myset");
513 benchmark("SPOP",cmd,len);
514 free(cmd);
515
516 len = redisFormatCommand(&cmd,"LPUSH mylist %s",data);
517 benchmark("LPUSH (again, in order to bench LRANGE)",cmd,len);
518 free(cmd);
519
520 len = redisFormatCommand(&cmd,"LRANGE mylist 0 99");
521 benchmark("LRANGE (first 100 elements)",cmd,len);
522 free(cmd);
523
524 len = redisFormatCommand(&cmd,"LRANGE mylist 0 299");
525 benchmark("LRANGE (first 300 elements)",cmd,len);
526 free(cmd);
527
528 len = redisFormatCommand(&cmd,"LRANGE mylist 0 449");
529 benchmark("LRANGE (first 450 elements)",cmd,len);
530 free(cmd);
531
532 len = redisFormatCommand(&cmd,"LRANGE mylist 0 599");
533 benchmark("LRANGE (first 600 elements)",cmd,len);
534 free(cmd);
535
536 printf("\n");
537 } while(config.loop);
538
539 return 0;
540 }