1
0

test_threads.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "pocketpy/common/threads.h"
  2. #include <stdio.h>
  3. int64_t time_monotonic_ns();
  4. static void func(void* arg) {
  5. long long* val = (long long*)arg;
  6. long long sum = 0;
  7. for(int i = 0; i < 100000; i++) {
  8. sum += *val;
  9. }
  10. *val = sum;
  11. }
  12. int main(int argc, char** argv) {
  13. int threads_num = 16;
  14. if(argc == 2) threads_num = atoi(argv[1]);
  15. printf("Using %d threads in the thread pool.\n", threads_num);
  16. c11_thrdpool pool;
  17. c11_thrdpool__ctor(&pool, threads_num);
  18. int num_tasks = 10000;
  19. long long* data = PK_MALLOC(sizeof(long long) * num_tasks);
  20. void** args = PK_MALLOC(sizeof(void*) * num_tasks);
  21. for(int i = 0; i < 10; i++) {
  22. for(int i = 0; i < num_tasks; i++) {
  23. data[i] = i;
  24. args[i] = &data[i];
  25. }
  26. printf("==> %dth run\n", i + 1);
  27. int64_t start_ns = time_monotonic_ns();
  28. c11_thrdpool__map(&pool, func, args, num_tasks);
  29. c11_thrdpool__join(&pool);
  30. int64_t end_ns = time_monotonic_ns();
  31. printf("==> %lld -> %lld\n", (long long)start_ns, (long long)end_ns);
  32. double elapsed = (end_ns - start_ns) / 1e9;
  33. printf(" Results: %lld, %lld, %lld, %lld, %lld\n",
  34. data[0],
  35. data[1],
  36. data[2],
  37. data[100],
  38. data[400]);
  39. printf(" Elapsed time for %d tasks: %.6f seconds\n", num_tasks, elapsed);
  40. for(int i = 0; i < 5000000; i++) {
  41. c11_thrd__yield();
  42. }
  43. }
  44. c11_thrdpool__dtor(&pool);
  45. PK_FREE(args);
  46. PK_FREE(data);
  47. return 0;
  48. }