fork_latency.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/time.h>
  5. #include <sys/wait.h>
  6. #include <unistd.h>
  7. #define DO_BENCH 1
  8. #define NTRIES 100
  9. #define TEST_TIMES 64
  10. int pids[TEST_TIMES];
  11. int main(int argc, char** argv) {
  12. int times = TEST_TIMES;
  13. int pipes[6];
  14. int i = 0;
  15. if (argc >= 2) {
  16. times = atoi(argv[1]);
  17. if (times > TEST_TIMES)
  18. return -1;
  19. }
  20. pipe(&pipes[0]);
  21. pipe(&pipes[2]);
  22. pipe(&pipes[4]);
  23. for (i = 0; i < times; i++) {
  24. pids[i] = fork();
  25. if (pids[i] < 0) {
  26. printf("fork failed\n");
  27. return -1;
  28. }
  29. if (pids[i] == 0) {
  30. close(pipes[1]);
  31. close(pipes[2]);
  32. close(pipes[5]);
  33. char byte;
  34. read(pipes[0], &byte, 1);
  35. struct timeval timevals[2];
  36. gettimeofday(&timevals[0], NULL);
  37. for (int count = 0; count < NTRIES; count++) {
  38. int child = fork();
  39. if (!child)
  40. exit(0);
  41. if (child > 0)
  42. waitpid(child, NULL, 0);
  43. }
  44. gettimeofday(&timevals[1], NULL);
  45. close(pipes[0]);
  46. write(pipes[3], timevals, sizeof(struct timeval) * 2);
  47. close(pipes[3]);
  48. read(pipes[4], &byte, 1);
  49. close(pipes[4]);
  50. exit(0);
  51. }
  52. }
  53. close(pipes[0]);
  54. close(pipes[3]);
  55. close(pipes[4]);
  56. sleep(1);
  57. char bytes[times];
  58. write(pipes[1], bytes, times);
  59. close(pipes[1]);
  60. unsigned long long start_time = 0;
  61. unsigned long long end_time = 0;
  62. unsigned long long total_time = 0;
  63. struct timeval timevals[2];
  64. for (int i = 0; i < times; i++) {
  65. read(pipes[2], timevals, sizeof(struct timeval) * 2);
  66. unsigned long s = timevals[0].tv_sec * 1000000ULL + timevals[0].tv_usec;
  67. unsigned long e = timevals[1].tv_sec * 1000000ULL + timevals[1].tv_usec;
  68. if (!start_time || s < start_time)
  69. start_time = s;
  70. if (!end_time || e > end_time)
  71. end_time = e;
  72. total_time += e - s;
  73. }
  74. close(pipes[2]);
  75. write(pipes[5], bytes, times);
  76. close(pipes[5]);
  77. for (i = 0; i < times; i++) {
  78. waitpid(pids[i], NULL, 0);
  79. }
  80. printf(
  81. "%d processes fork %d children: throughput = %lf procs/second, "
  82. "latency = %lf microseconds\n",
  83. times, NTRIES, 1.0 * NTRIES * times * 1000000 / (end_time - start_time),
  84. 1.0 * total_time / (NTRIES * times));
  85. return 0;
  86. }