0001
0002 #include <malloc.h>
0003 #include <stdlib.h>
0004 #include <string.h>
0005 #include <time.h>
0006 #include "utils.h"
0007
0008 #define SIZE 256
0009 #define ITERATIONS 1000
0010 #define ITERATIONS_BENCH 100000
0011
0012 int test_strlen(const void *s);
0013
0014
0015 static void test_one(char *s)
0016 {
0017 unsigned long offset;
0018
0019 for (offset = 0; offset < SIZE; offset++) {
0020 int x, y;
0021 unsigned long i;
0022
0023 y = strlen(s + offset);
0024 x = test_strlen(s + offset);
0025
0026 if (x != y) {
0027 printf("strlen() returned %d, should have returned %d (%p offset %ld)\n", x, y, s, offset);
0028
0029 for (i = offset; i < SIZE; i++)
0030 printf("%02x ", s[i]);
0031 printf("\n");
0032 }
0033 }
0034 }
0035
0036 static void bench_test(char *s)
0037 {
0038 struct timespec ts_start, ts_end;
0039 int i;
0040
0041 clock_gettime(CLOCK_MONOTONIC, &ts_start);
0042
0043 for (i = 0; i < ITERATIONS_BENCH; i++)
0044 test_strlen(s);
0045
0046 clock_gettime(CLOCK_MONOTONIC, &ts_end);
0047
0048 printf("len %3.3d : time = %.6f\n", test_strlen(s), ts_end.tv_sec - ts_start.tv_sec + (ts_end.tv_nsec - ts_start.tv_nsec) / 1e9);
0049 }
0050
0051 static int testcase(void)
0052 {
0053 char *s;
0054 unsigned long i;
0055
0056 s = memalign(128, SIZE);
0057 if (!s) {
0058 perror("memalign");
0059 exit(1);
0060 }
0061
0062 srandom(1);
0063
0064 memset(s, 0, SIZE);
0065 for (i = 0; i < SIZE; i++) {
0066 char c;
0067
0068 do {
0069 c = random() & 0x7f;
0070 } while (!c);
0071 s[i] = c;
0072 test_one(s);
0073 }
0074
0075 for (i = 0; i < ITERATIONS; i++) {
0076 unsigned long j;
0077
0078 for (j = 0; j < SIZE; j++) {
0079 char c;
0080
0081 do {
0082 c = random() & 0x7f;
0083 } while (!c);
0084 s[j] = c;
0085 }
0086 for (j = 0; j < sizeof(long); j++) {
0087 s[SIZE - 1 - j] = 0;
0088 test_one(s);
0089 }
0090 }
0091
0092 for (i = 0; i < SIZE; i++) {
0093 char c;
0094
0095 do {
0096 c = random() & 0x7f;
0097 } while (!c);
0098 s[i] = c;
0099 }
0100
0101 bench_test(s);
0102
0103 s[16] = 0;
0104 bench_test(s);
0105
0106 s[8] = 0;
0107 bench_test(s);
0108
0109 s[4] = 0;
0110 bench_test(s);
0111
0112 s[3] = 0;
0113 bench_test(s);
0114
0115 s[2] = 0;
0116 bench_test(s);
0117
0118 s[1] = 0;
0119 bench_test(s);
0120
0121 return 0;
0122 }
0123
0124 int main(void)
0125 {
0126 return test_harness(testcase, "strlen");
0127 }