-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreading.h
More file actions
69 lines (50 loc) · 1.56 KB
/
Copy paththreading.h
File metadata and controls
69 lines (50 loc) · 1.56 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
#pragma once
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
//timing struct for printing its lifetime (measuring time of its existence)
struct Timer
{
std::string name;
std::chrono::time_point<std::chrono::system_clock> start;
std::chrono::duration<float> duration;
Timer(std::string name) : name(name)
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
duration = std::chrono::high_resolution_clock::now() - start;
std::cout << "Timer " << name << ": " << 1000*duration.count() << " ms\n";
}
};
//simple for loop on multiple threads
template<typename func, typename... args>
double threadProbabilityFor(int numOfThreads, int repeats, func f, args... a)
{
std::vector<double> outputParts;
outputParts.reserve(numOfThreads);
std::mutex output_mutex;
auto forPart = [&](int begin, int partRepeats){
double outputPart = 0;
for (int i = begin; i < partRepeats + begin; ++i) outputPart += f(i, a...);
std::lock_guard<std::mutex> guard(output_mutex);
outputParts.push_back(outputPart);
};
int part = repeats / numOfThreads;
int remainder = repeats % numOfThreads;
std::vector<std::thread> threads;
threads.reserve(numOfThreads);
for (int i = 0; i < numOfThreads; ++i)
{
int extra = i < remainder ? i : remainder;
int begin = i*part + extra;
threads.push_back(std::thread(forPart, begin, part + (i < remainder)));
}
for (int i = 0; i < numOfThreads; ++i) threads[i].join();
double output = 0;
for(double outputPart : outputParts) output += outputPart;
return output;
}