forked from xxyzz/ostep-hw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.c
66 lines (58 loc) · 1.84 KB
/
1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sched.h>
int
main(int argc, char *argv[]) {
// measure system call
int fd = open("./1.txt", O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU), nloops = 1000000;
struct timeval start, end;
gettimeofday(&start, NULL);
for (size_t i = 0; i < nloops; i++) {
read(fd, NULL, 0);
}
gettimeofday(&end, NULL);
printf("system call: %f microseconds\n\n", (float) (end.tv_sec * 1000000 + end.tv_usec - start.tv_sec * 1000000 - start.tv_usec) / nloops);
close(fd);
// measure context switch
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(0, &set);
int first_pipefd[2], second_pipefd[2];
if (pipe(first_pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
if (pipe(second_pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (cpid == 0) { // child
if (sched_setaffinity(getpid(), sizeof(cpu_set_t), &set) == -1) {
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < nloops; i++) {
read(first_pipefd[0], NULL, 0);
write(second_pipefd[1], NULL, 0);
}
} else { // parent
if (sched_setaffinity(getpid(), sizeof(cpu_set_t), &set) == -1) {
exit(EXIT_FAILURE);
}
gettimeofday(&start, NULL);
for (size_t i = 0; i < nloops; i++) {
write(first_pipefd[1], NULL, 0);
read(second_pipefd[0], NULL, 0);
}
gettimeofday(&end, NULL);
printf("context switch: %f microseconds\n", (float) (end.tv_sec * 1000000 + end.tv_usec - start.tv_sec * 1000000 - start.tv_usec) / nloops);
}
return 0;
}