fork_latency.c 2.6 KB

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