fork_latency.c 2.8 KB

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