compose-traversal.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright © 2023 Pierre Le Marre
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #include <string.h>
  7. #include <time.h>
  8. #include "xkbcommon/xkbcommon-compose.h"
  9. #include "../test/compose-iter.h"
  10. #include "../test/test.h"
  11. #include "bench.h"
  12. #define BENCHMARK_ITERATIONS 1000
  13. static void
  14. compose_fn(struct xkb_compose_table_entry *entry, void *data)
  15. {
  16. assert (entry);
  17. }
  18. /* Benchmark compose traversal using:
  19. * • the internal recursive function `xkb_compose_table_for_each` if `foreach` is
  20. * is passed as argument to the program;
  21. * • else the iterator API (`xkb_compose_table_iterator_new`, …).
  22. */
  23. int
  24. main(int argc, char *argv[])
  25. {
  26. struct xkb_context *ctx;
  27. char *path;
  28. FILE *file;
  29. struct xkb_compose_table *table;
  30. struct bench bench;
  31. char *elapsed;
  32. bool use_foreach_impl = (argc > 1 && strcmp(argv[1], "foreach") == 0);
  33. ctx = test_get_context(CONTEXT_NO_FLAG);
  34. assert(ctx);
  35. path = test_get_path("locale/en_US.UTF-8/Compose");
  36. file = fopen(path, "rb");
  37. if (file == NULL) {
  38. perror(path);
  39. free(path);
  40. xkb_context_unref(ctx);
  41. return -1;
  42. }
  43. free(path);
  44. xkb_enable_quiet_logging(ctx);
  45. table = xkb_compose_table_new_from_file(ctx, file, "",
  46. XKB_COMPOSE_FORMAT_TEXT_V1,
  47. XKB_COMPOSE_COMPILE_NO_FLAGS);
  48. fclose(file);
  49. assert(table);
  50. bench_start(&bench);
  51. for (int i = 0; i < BENCHMARK_ITERATIONS; i++) {
  52. if (use_foreach_impl) {
  53. xkb_compose_table_for_each(table, compose_fn, NULL);
  54. } else {
  55. struct xkb_compose_table_iterator *iter;
  56. struct xkb_compose_table_entry *entry;
  57. iter = xkb_compose_table_iterator_new(table);
  58. while ((entry = xkb_compose_table_iterator_next(iter))) {
  59. assert (entry);
  60. }
  61. xkb_compose_table_iterator_free(iter);
  62. }
  63. }
  64. bench_stop(&bench);
  65. xkb_compose_table_unref(table);
  66. elapsed = bench_elapsed_str(&bench);
  67. fprintf(stderr, "traversed %d compose tables in %ss\n",
  68. BENCHMARK_ITERATIONS, elapsed);
  69. free(elapsed);
  70. xkb_context_unref(ctx);
  71. return 0;
  72. }