fork_latency.c 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. gettimeofday(&timevals[1], NULL);
  48. close(pipes[0]);
  49. write(pipes[3], timevals, sizeof(struct timeval) * 2);
  50. close(pipes[3]);
  51. read(pipes[4], &byte, 1);
  52. close(pipes[4]);
  53. exit(0);
  54. }
  55. }
  56. close(pipes[0]);
  57. close(pipes[3]);
  58. close(pipes[4]);
  59. sleep(1);
  60. char bytes[times];
  61. write(pipes[1], bytes, times);
  62. close(pipes[1]);
  63. unsigned long long start_time = 0;
  64. unsigned long long end_time = 0;
  65. unsigned long long total_time = 0;
  66. struct timeval timevals[2];
  67. for (int i = 0 ; i < times ; i++) {
  68. read(pipes[2], timevals, sizeof(struct timeval) * 2);
  69. unsigned long s = timevals[0].tv_sec * 1000000ULL +
  70. timevals[0].tv_usec;
  71. unsigned long e = timevals[1].tv_sec * 1000000ULL +
  72. timevals[1].tv_usec;
  73. if (!start_time || s < start_time)
  74. start_time = s;
  75. if (!end_time || e > end_time)
  76. end_time = e;
  77. total_time += e - s;
  78. }
  79. close(pipes[2]);
  80. write(pipes[5], bytes, times);
  81. close(pipes[5]);
  82. for (i = 0 ; i < times ; i++)
  83. waitpid(pids[i], NULL, 0);
  84. printf("%d processes fork %d children: throughput = %lf procs/second, "
  85. "latency = %lf microseconds\n",
  86. times, NTRIES,
  87. 1.0 * NTRIES * times * 1000000 / (end_time - start_time),
  88. 1.0 * total_time / (NTRIES * times));
  89. return 0;
  90. }