1 #undef G_DISABLE_ASSERT
9 #include <sys/resource.h>
16 static int n_children
= 3;
17 static int n_active_children
;
18 static int n_iters
= 10000;
20 static int write_fds
[1024];
21 static struct pollfd poll_fds
[1024];
29 fprintf (stderr
, "Cannot create pipe %s\n", strerror (errsv
));
35 read_all (int fd
, char *buf
, int len
)
37 size_t bytes_read
= 0;
40 while (bytes_read
< len
)
42 count
= read (fd
, buf
+ bytes_read
, len
- bytes_read
);
58 write_all (int fd
, char *buf
, int len
)
60 size_t bytes_written
= 0;
63 while (bytes_written
< len
)
65 count
= write (fd
, buf
+ bytes_written
, len
- bytes_written
);
72 bytes_written
+= count
;
79 run_child (int in_fd
, int out_fd
)
84 for (i
= 0; i
< n_iters
; i
++)
86 write_all (out_fd
, (char *)&val
, sizeof (val
));
87 read_all (in_fd
, (char *)&val
, sizeof (val
));
91 write_all (out_fd
, (char *)&val
, sizeof (val
));
97 input_callback (int source
, int dest
)
101 if (!read_all (source
, (char *)&val
, sizeof(val
)))
103 fprintf (stderr
,"Unexpected EOF\n");
109 write_all (dest
, (char *)&val
, sizeof(val
));
123 create_child (int pos
)
135 if (pid
> 0) /* Parent */
140 write_fds
[pos
] = in_fds
[1];
141 poll_fds
[pos
].fd
= out_fds
[0];
142 poll_fds
[pos
].events
= POLLIN
;
144 else if (pid
== 0) /* Child */
151 run_child (in_fds
[0], out_fds
[1]);
155 fprintf (stderr
,"Cannot fork: %s\n", strerror (errsv
));
161 difftimeval (struct timeval
*old
, struct timeval
*new)
164 (new->tv_sec
- old
->tv_sec
) * 1000. + (new->tv_usec
- old
->tv_usec
) / 1000;
168 main (int argc
, char **argv
)
171 struct rusage old_usage
;
172 struct rusage new_usage
;
175 n_children
= atoi(argv
[1]);
178 n_iters
= atoi(argv
[2]);
180 printf ("Children: %d Iters: %d\n", n_children
, n_iters
);
182 n_active_children
= n_children
;
183 for (i
= 0; i
< n_children
; i
++)
186 getrusage (RUSAGE_SELF
, &old_usage
);
188 while (n_active_children
> 0)
190 int old_n_active_children
= n_active_children
;
192 poll (poll_fds
, n_active_children
, -1);
194 for (i
=0; i
<n_active_children
; i
++)
196 if (poll_fds
[i
].events
& (POLLIN
| POLLHUP
))
198 if (!input_callback (poll_fds
[i
].fd
, write_fds
[i
]))
203 if (old_n_active_children
> n_active_children
)
206 for (i
=0; i
<old_n_active_children
; i
++)
208 if (write_fds
[i
] != -1)
212 poll_fds
[j
] = poll_fds
[i
];
213 write_fds
[j
] = write_fds
[i
];
221 getrusage (RUSAGE_SELF
, &new_usage
);
223 printf ("Elapsed user: %g\n",
224 difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
));
225 printf ("Elapsed system: %g\n",
226 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
));
227 printf ("Elapsed total: %g\n",
228 difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
) +
229 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
));
230 printf ("total / iteration: %g\n",
231 (difftimeval (&old_usage
.ru_utime
, &new_usage
.ru_utime
) +
232 difftimeval (&old_usage
.ru_stime
, &new_usage
.ru_stime
)) /
233 (n_iters
* n_children
));