I'm trying to find the time in microseconds it takes to cycle a char through a pipe
currently this is what I have, but the results are negative somehow
Code:
clock_t cs_do_child(int input_pipe[], int output_pipe[])
{
char ch; /* character we are cycling */
clock_t done; /* clock time after writing */
close(input_pipe[1]);
close(output_pipe[0]);
if (read(input_pipe[0], &ch, 1) > 0)
{
if (write(output_pipe[1], &ch, 1) == -1)
{
perror("Child write");
close(input_pipe[0]);
close(output_pipe[1]);
exit(1);
}
}
done = clock();
close(input_pipe[0]);
close(output_pipe[1]);
return done;
}
clock_t cs_do_parent(int input_pipe[], int output_pipe[])
{
char ch = 'a'; /* character to cycle */
clock_t start; /* clock time before write */
close(input_pipe[1]);
close(output_pipe[0]);
start = clock();
if (write(output_pipe[1], &ch, 1) == -1)
{
perror("Parent write");
close(input_pipe[0]);
close(output_pipe[1]);
exit(1);
}
if (read(input_pipe[0], &ch, 1) <= 0)
{
perror("Parent read");
close(input_pipe[0]);
close(output_pipe[1]);
exit(1);
}
close(input_pipe[0]);
close(output_pipe[1]);
return start;
}
void context_switch()
{
int child_to_parent[2];
int parent_to_child[2];
pid_t child_pid;
clock_t start, finish;
double benchmark;
if (pipe(child_to_parent) == -1)
{
perror("Create pipe: child_to_parent");
exit(1);
}
if (pipe(parent_to_child) == -1)
{
perror("Create pipe: parent_to_child");
exit(1);
}
child_pid = fork();
switch(child_pid) {
case -1: perror("fork"); exit(1);
case 0: finish = cs_do_child(parent_to_child, child_to_parent); exit(0);
default: start = cs_do_parent(child_to_parent, parent_to_child); break;
}
benchmark = ((double)(finish - start)) / CLOCKS_PER_SEC;
printf("%f\n", benchmark);
}
yes, dividing by CLOCKS_PER_SEC gives me seconds, not microseconds, but right now I'm just trying to get realistic output, and will change it later.
Output:
-12.854472