-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbenchmark.cpp
64 lines (47 loc) · 1.81 KB
/
benchmark.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
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include <functional>
#include "ThreadLibrary.h"
// Function to be executed by each thread
void printMessage(int threadId) {
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Simulate work
}
// Function to benchmark the custom thread library
void benchmarkCustomThreadLibrary(int numThreads) {
ThreadLibrary threadLib;
auto start = std::chrono::high_resolution_clock::now();
// Create and run threads
threadLib.createAndRunThreads(numThreads, printMessage);
// Join all threads
threadLib.joinAllThreads();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "Time taken with custom thread library: " << elapsed_seconds.count() << " seconds" << std::endl;
}
// Function to benchmark the C++ <thread> library
void benchmarkStdThreadLibrary(int numThreads) {
std::vector<std::thread> threads;
auto start = std::chrono::high_resolution_clock::now();
// Create and run threads
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(printMessage, i);
}
// Join all threads
for (auto& t : threads) {
t.join();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "Time taken with std::thread library: " << elapsed_seconds.count() << " seconds" << std::endl;
}
int main() {
int numThreads = 9999; // Number of threads to create
std::cout << "Benchmarking with " << numThreads << " threads:" << std::endl;
// Benchmark std::thread library
benchmarkStdThreadLibrary(numThreads);
// Benchmark custom thread library
benchmarkCustomThreadLibrary(numThreads);
return 0;
}