-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext-switch.cpp
More file actions
90 lines (80 loc) · 2.17 KB
/
Copy pathcontext-switch.cpp
File metadata and controls
90 lines (80 loc) · 2.17 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sched.h>
#include <iostream>
#include <vector>
#include "stdev.h"
#include "time/rdtscp_timer.h"
#include "hdr.h"
const int ITERATIONS = 1'000'000;
const std::string EXPERIMENT_HDR_NAME = "context-switch.hdr";
int main(int argc, char *argv[])
{
RdtscpTimer timer;
std::vector<double> measurements;
measurements.reserve(ITERATIONS);
// 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 p_id = fork();
if (p_id == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if (p_id == 0)
{ // child
if (sched_setaffinity(getpid(), sizeof(cpu_set_t), &set) == -1)
{
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < ITERATIONS; i++)
{
int len;
len = read(first_pipefd[0], NULL, 0);
if (len < 0)
std::cerr << "could not read! " << p_id << "\n";
len = write(second_pipefd[1], NULL, 0);
if (len < 0)
std::cerr << "could not write! " << p_id << "\n";
}
}
else
{ // parent
if (sched_setaffinity(getpid(), sizeof(cpu_set_t), &set) == -1)
{
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < ITERATIONS; i++)
{
int len;
timer.start();
len = write(first_pipefd[1], NULL, 0);
if (len < 0)
std::cerr << "could not write! " << p_id << "\n";
len = read(second_pipefd[0], NULL, 0);
if (len < 0)
std::cerr << "could not read! " << p_id << "\n";
timer.finish();
measurements.push_back(timer.duration());
}
std::cout << "process context switch cycles:\n";
vec_print(measurements);
print_hdr(measurements, EXPERIMENT_HDR_NAME);
}
return 0;
}