strlen.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <malloc.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <time.h>
  6. #include "utils.h"
  7. #define SIZE 256
  8. #define ITERATIONS 1000
  9. #define ITERATIONS_BENCH 100000
  10. int test_strlen(const void *s);
  11. /* test all offsets and lengths */
  12. static void test_one(char *s)
  13. {
  14. unsigned long offset;
  15. for (offset = 0; offset < SIZE; offset++) {
  16. int x, y;
  17. unsigned long i;
  18. y = strlen(s + offset);
  19. x = test_strlen(s + offset);
  20. if (x != y) {
  21. printf("strlen() returned %d, should have returned %d (%p offset %ld)\n", x, y, s, offset);
  22. for (i = offset; i < SIZE; i++)
  23. printf("%02x ", s[i]);
  24. printf("\n");
  25. }
  26. }
  27. }
  28. static void bench_test(char *s)
  29. {
  30. struct timespec ts_start, ts_end;
  31. int i;
  32. clock_gettime(CLOCK_MONOTONIC, &ts_start);
  33. for (i = 0; i < ITERATIONS_BENCH; i++)
  34. test_strlen(s);
  35. clock_gettime(CLOCK_MONOTONIC, &ts_end);
  36. 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);
  37. }
  38. static int testcase(void)
  39. {
  40. char *s;
  41. unsigned long i;
  42. s = memalign(128, SIZE);
  43. if (!s) {
  44. perror("memalign");
  45. exit(1);
  46. }
  47. srandom(1);
  48. memset(s, 0, SIZE);
  49. for (i = 0; i < SIZE; i++) {
  50. char c;
  51. do {
  52. c = random() & 0x7f;
  53. } while (!c);
  54. s[i] = c;
  55. test_one(s);
  56. }
  57. for (i = 0; i < ITERATIONS; i++) {
  58. unsigned long j;
  59. for (j = 0; j < SIZE; j++) {
  60. char c;
  61. do {
  62. c = random() & 0x7f;
  63. } while (!c);
  64. s[j] = c;
  65. }
  66. for (j = 0; j < sizeof(long); j++) {
  67. s[SIZE - 1 - j] = 0;
  68. test_one(s);
  69. }
  70. }
  71. for (i = 0; i < SIZE; i++) {
  72. char c;
  73. do {
  74. c = random() & 0x7f;
  75. } while (!c);
  76. s[i] = c;
  77. }
  78. bench_test(s);
  79. s[16] = 0;
  80. bench_test(s);
  81. s[8] = 0;
  82. bench_test(s);
  83. s[4] = 0;
  84. bench_test(s);
  85. s[3] = 0;
  86. bench_test(s);
  87. s[2] = 0;
  88. bench_test(s);
  89. s[1] = 0;
  90. bench_test(s);
  91. return 0;
  92. }
  93. int main(void)
  94. {
  95. return test_harness(testcase, "strlen");
  96. }