Created
September 21, 2015 07:40
-
-
Save greensea/816b0f2b325b98d3ecb1 to your computer and use it in GitHub Desktop.
测试字符串比较函数的性能
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <time.h> | |
#include "sds.h" | |
/** | |
* 高效地比较两个字符串的大小 | |
*/ | |
static inline int sdscmp4(const sds s1, const sds s2) { | |
size_t l1, l2; | |
int d; | |
l1 = sdslen(s1); | |
l2 = sdslen(s2); | |
d = l1 - l2; | |
/// 长度更短的字符串更小 | |
if (d < 0) { | |
return -1; | |
} | |
else if (d > 0) { | |
return 1; | |
} | |
/// 如果长度相同,则进行常规比较 | |
char *ss1, *ss2; | |
ss1 = s1; | |
ss2 = s2; | |
while (l1 > 0) { | |
if (*(uint64_t*)ss1 > *(uint64_t*)ss2) { | |
return 1; | |
} | |
else if (*(uint64_t*)ss1 < *(uint64_t*)ss2) { | |
return -1; | |
} | |
else { | |
ss1 += 8; | |
ss2 += 8; | |
l1 -= 8; | |
} | |
} | |
return 0; | |
} | |
/** | |
* @param int 字符串长度(不含末尾 \0) | |
* @param int 循环次数,单位是千次 | |
*/ | |
void strcmp_bench(int len, int kloops) { | |
char **s1, **s2; | |
sds *sd1, *sd2; | |
clock_t t_nop, t1, t2; | |
int i, k, ret; | |
s1 = malloc(kloops * sizeof(char*)); | |
s2 = malloc(kloops * sizeof(char*)); | |
sd1 = malloc(kloops * sizeof(sds)); | |
sd2 = malloc(kloops * sizeof(sds)); | |
for (i = 0; i < kloops; i++) { | |
s1[i] = malloc(len + 1); | |
memset(s1[i], 'a', len); | |
s1[i][len] = 0x00; | |
s2[i] = strdup(s1[i]); | |
s2[i][len - 1] = 0x00; | |
sd1[i] = sdsnew(s1[i]); | |
sd2[i] = sdsnew(s2[i]); | |
} | |
ret = 0; | |
t1 = clock(); | |
for (k = 0; k < 1000; k++) { | |
for (i = 0; i < kloops; i++) { | |
ret += len; | |
} | |
} | |
t_nop = clock() - t1; | |
printf("ret=%d\n", ret); | |
printf("空循环耗时 %0.3lf 秒\n", t_nop / (double)CLOCKS_PER_SEC); | |
ret = 0; | |
t1 = clock(); | |
for (k = 0; k < 1000; k++) { | |
for (i = 0; i < kloops; i++) { | |
ret += strcmp(s1[i], s2[i]); | |
} | |
} | |
t2 = clock() - t1; | |
printf("ret=%d\n", ret); | |
printf("strcmp 循环耗时 %0.3lf 秒\n", t2 / (double)CLOCKS_PER_SEC); | |
ret = 0; | |
t1 = clock(); | |
for (k = 0; k < 1000; k++) { | |
for (i = 0; i < kloops; i++) { | |
ret += sdscmp(sd1[i], sd2[i]); | |
} | |
} | |
t2 = clock() - t1; | |
printf("ret=%d\n", ret); | |
printf("sdscmp 循环耗时 %0.3lf 秒\n", t2 / (double)CLOCKS_PER_SEC); | |
ret = 0; | |
t1 = clock(); | |
for (k = 0; k < 1000; k++) { | |
for (i = 0; i < kloops; i++) { | |
ret += sdscmp4(sd1[i], sd2[i]); | |
} | |
} | |
t2 = clock() - t1; | |
printf("ret=%d\n", ret); | |
printf("sdscmp4 循环耗时 %0.3lf 秒\n", t2 / (double)CLOCKS_PER_SEC); | |
} | |
int main() { | |
strcmp_bench(3200, 1000); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment