Skip to content

Instantly share code, notes, and snippets.

@john9francis
Last active July 12, 2024 17:29
Show Gist options
  • Save john9francis/95f5cd73e04d3aaa2f4bceccd68d48f3 to your computer and use it in GitHub Desktop.
Save john9francis/95f5cd73e04d3aaa2f4bceccd68d48f3 to your computer and use it in GitHub Desktop.
This simple program has a function that should take 5 seconds. The program creates a user-defined number of threads that each execute the function. This was to test how many threads c++ can handle.
// testing how many threads work in c++
// spoiler alert: at least 2000 work, probably more
#include <thread>
#include <iostream>
#include <chrono>
#include <vector>
void count(int threadNumber){
// Function that counts 5 seconds
int seconds = 5;
int timeDelay = 1;
for (int i=0; i<seconds; i++){
std::cout
<< "Thread: "
<< threadNumber
<< " Count: "
<< i
<< std::endl;
std::this_thread::sleep_for(std::chrono::seconds(timeDelay));
}
}
int main(int argc, char *argv[]){
// Allows number of threads to be passed in as an argument.
// checks to make sure it's a valid int and then goes from there
if (argc != 2){
std::cout
<< "Please specify number of threads with exactly one argument."
<< std::endl
<< "For example: .\\main.exe 12"
<< std::endl;
return 1;
}
int nThreads;
try {
nThreads = std::stoi(argv[1]);
} catch (const std::invalid_argument &e) {
std::cerr << "Invalid number: " << argv[1] << std::endl;
return 1;
} catch (const std::out_of_range &e) {
std::cerr << "Number out of range: " << argv[1] << std::endl;
return 1;
}
std::vector<std::thread> threads;
// start time to see how long this program takes to finish
auto start = std::chrono::high_resolution_clock::now();
for (int i=0; i<nThreads; i++){
threads.emplace_back(count, i);
}
for (auto &t: threads){
t.join();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "The program took " << duration.count() << " seconds to complete." << std::endl;
}
// conclusions:
// 0-200 or so threads takes 5 seconds.
// 1000 threads takes 5.5 seconds
// 2000 threads takes 6.5 or so
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment