-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext-switch-thread.cpp
73 lines (64 loc) · 1.58 KB
/
context-switch-thread.cpp
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
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sched.h>
#include <iostream>
#include <vector>
#include <thread>
#include "time/rdtscp_timer.h"
#include "hdr.h"
const int ITERATIONS = 1'000'000;
const std::string EXPERIMENT_HDR_NAME = "context-switch.hdr";
int first_pipefd[2], second_pipefd[2];
void pong()
{
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! pong\n";
len = write(second_pipefd[1], NULL, 0);
if (len < 0)
std::cerr << "could not write! pong\n";
}
}
void setup_pipes()
{
if (pipe(first_pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if (pipe(second_pipefd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
RdtscpTimer timer;
std::vector<double> measurements;
measurements.reserve(ITERATIONS);
setup_pipes();
std::thread ping_thread(pong);
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! ping\n";
len = read(second_pipefd[0], NULL, 0);
if (len < 0)
std::cerr << "could not read! ping\n";
timer.finish();
measurements.push_back(timer.duration());
}
std::cout << "thread context switch cycles:\n";
print_hdr(measurements);
ping_thread.join();
return 0;
}