-
Notifications
You must be signed in to change notification settings - Fork 0
/
graveler_challenge_cpu.cpp
62 lines (48 loc) · 1.79 KB
/
graveler_challenge_cpu.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
#include <iostream>
#include <vector>
#include <random>
#include <thread>
#include <mutex>
#include <chrono>
#include <iomanip> // Include this header for std::fixed and std::setprecision
#define NUM_ITEMS 4
#define NUM_ROLLS 231
#define NUM_SIMULATIONS 1000000000 // 1,000,000,000
#define NUM_THREADS 8 // Adjust based on your CPU's number of cores
std::mutex maxOnesMutex;
int maxOnes = 0;
void simulateRolls(int threadId, int simulationsPerThread, std::mt19937 &gen, std::uniform_int_distribution<int> &dist) {
for (int i = 0; i < simulationsPerThread; ++i) {
int counts[NUM_ITEMS] = {0};
for (int j = 0; j < NUM_ROLLS; ++j) {
int roll = dist(gen);
counts[roll]++;
}
int ones = counts[0];
std::lock_guard<std::mutex> guard(maxOnesMutex);
if (ones > maxOnes) {
maxOnes = ones;
}
}
}
int main() {
int simulationsPerThread = NUM_SIMULATIONS / NUM_THREADS;
std::vector<std::thread> threads;
std::random_device rd;
// Start timing
auto start = std::chrono::high_resolution_clock::now();
for (int t = 0; t < NUM_THREADS; ++t) {
std::mt19937 gen(rd() + t); // Seed with different values for each thread
std::uniform_int_distribution<int> dist(0, NUM_ITEMS - 1);
threads.emplace_back(simulateRolls, t, simulationsPerThread, std::ref(gen), std::ref(dist));
}
for (auto &thread : threads) {
thread.join();
}
// End timing
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
std::cout << "Highest Ones Roll: " << maxOnes << std::endl;
std::cout << "Execution time: " << std::fixed << std::setprecision(6) << elapsed.count() << " seconds" << std::endl;
return 0;
}