Skip to content
Snippets Groups Projects
Commit d84e8f2e authored by Erik Strand's avatar Erik Strand
Browse files

Add pi calculation using manually spawned threads

parent af6fa97b
Branches
No related tags found
No related merge requests found
# This Makefile compiles and flashes four different programs:
CPPFLAGS=-Wall -O3 -pthread -std=c++11
CPPFLAGS=-Wall -O3 -pthread -std=c++11 -ffast-math
%: %.cpp
g++ $(CPPFLAGS) -o build/$@ $<
......
#include <array>
#include <chrono>
#include <iostream>
#include <numeric>
#include <thread>
int main() {
constexpr double a = 0.5;
constexpr double b = 0.75;
constexpr double c = 0.25;
// n_threads * n_iterations_per_thread + 1 must fit in a uint32_t
constexpr uint32_t n_threads = 4u;
constexpr uint32_t n_iterations_per_thread = 100000000u;
std::array<std::thread, n_threads> threads;
std::array<double, n_threads> thread_results;
const auto pi_sum = [&](uint32_t index) {
double& value = thread_results[index];
value = 0;
const uint32_t i_begin = n_iterations_per_thread * index + 1;
const uint32_t i_end = n_iterations_per_thread * (index + 1);
for (uint32_t i = i_begin; i <= i_end; ++i) {
value += a / ((i - b) * (i - c));
}
};
const auto start_time = std::chrono::steady_clock::now();
for (auto i = 0u; i < n_threads; ++i) {
threads[i] = std::thread(pi_sum, i);
}
for (auto i = 0u; i < n_threads; ++i) {
threads[i].join();
}
const auto end_time = std::chrono::steady_clock::now();
double pi = std::accumulate(thread_results.begin(), thread_results.end(), double(0));
std::cout << "Final value: " << pi << '\n';
const auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
std::cout << "Time (microseconds): " << microseconds << '\n';
const auto mega_flops = n_threads * n_iterations_per_thread * 5.0 / microseconds;
std::cout << "MFLOPS: " << mega_flops << '\n';
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment