-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreaded_pi_calc_win32api.cpp
97 lines (79 loc) · 2.43 KB
/
threaded_pi_calc_win32api.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <windows.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <chrono>
#include <atomic>
// Block size for distribution
const int blockSize = 1308080;
// Total iterations
const int N = 100000000;
const int numBlocks = N / blockSize;
CRITICAL_SECTION cs;
std::atomic<int> nextBlock(0);
double pi = 0.0;
std::vector<bool> processedBlocks(numBlocks, false);
DWORD WINAPI CalculatePiBlock(LPVOID param)
{
while (true)
{
int blockIndex = nextBlock.fetch_add(1);
if (blockIndex >= numBlocks)
{
break;
}
double blockSum = 0.0;
int start = blockIndex * blockSize;
int end = start + blockSize;
for (int i = start; i < end; ++i)
{
double x = (i + 0.5) / N;
blockSum += 4.0 / (1.0 + x * x);
}
EnterCriticalSection(&cs);
pi += blockSum;
LeaveCriticalSection(&cs);
}
return 0;
}
void runCalculation(int numThreads)
{
InitializeCriticalSection(&cs);
std::vector<HANDLE> threads(numThreads);
std::vector<int> threadNums(numThreads);
for (int i = 0; i < numThreads; ++i)
{
threadNums[i] = i;
threads[i] = CreateThread(NULL, 0, CalculatePiBlock, &threadNums[i], 0, NULL);
}
WaitForMultipleObjects(numThreads, threads.data(), TRUE, INFINITE);
for (HANDLE thread : threads)
{
CloseHandle(thread);
}
DeleteCriticalSection(&cs);
}
int main()
{
std::vector<int> threadCounts = {1, 2, 4, 8, 12, 16, 32, 64};
std::ofstream resultsFile("threaded_pi_calc_win32api_results.txt");
resultsFile << "Threads, Time taken (s)" << std::endl;
for (int numThreads : threadCounts)
{
pi = 0.0;
nextBlock.store(0);
processedBlocks.assign(numBlocks, false);
// Start timing
std::cout << "Starting calculation with " << numThreads << " threads...\n";
auto startTime = std::chrono::high_resolution_clock::now();
// Perform the computation
runCalculation(numThreads);
// End timing
auto endTime = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = endTime - startTime;
std::cout << "Threads: " << numThreads << ", Time taken: " << duration.count() << " s, Calculated Pi: " << pi << "\n";
resultsFile << numThreads << ", " << duration.count() << std::endl;
}
resultsFile.close();
return 0;
}