-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
68 lines (52 loc) · 1.63 KB
/
main.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
#include "threadpool.h"
#include <iostream>
#include <future>
#include <fstream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <string.h>
long long fibonacci(int n) {
if (n <= 1)
return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
std::string getTime() {
time_t rawtime;
time (&rawtime);
std::string ctime_no_newline = strtok(ctime(&rawtime), "\n");
return "[" + ctime_no_newline + "]";
}
void run(std::ofstream &outFile, int &testNum) {
std::vector<std::future<long long>> futures;
futures.reserve(testNum);
clock_t start = clock();
for (int i = 0; i < testNum; i++)
futures.emplace_back(std::async(std::launch::async, fibonacci, i % 10));
for (auto &fut: futures)
fut.get();
outFile << "Time taken: " << (double)(clock() - start) / CLOCKS_PER_SEC << std::endl;
}
void runWithThreadPool(std::ofstream &outFile, int &testNum) {
threadpool::Threadpool pool;
int numOfThreads = 4;
pool.init(numOfThreads);
std::cout << "Thread pool size: " << pool.size() << std::endl;
std::vector<std::future<long long>> futures;
futures.reserve(testNum);
clock_t start = clock();
for (int i = 0; i < testNum; i++)
futures.emplace_back(pool.async(fibonacci, i % 10));
for (auto &fut: futures)
fut.get();
outFile << "Time taken for threadpool: " << (double)(clock() - start) / CLOCKS_PER_SEC << std::endl;
pool.terminate();
}
int main() {
std::ofstream outFile("output.txt");
int testNum = 2048;
runWithThreadPool(outFile, testNum);
run(outFile, testNum);
outFile.close();
return 0;
}