Skip to content

Instantly share code, notes, and snippets.

@HeMe2
Last active November 28, 2019 17:50
Show Gist options
  • Save HeMe2/33403d61958e3453bdd84d66eda0f44b to your computer and use it in GitHub Desktop.
Save HeMe2/33403d61958e3453bdd84d66eda0f44b to your computer and use it in GitHub Desktop.
Measures and prints the times for thread creation and mutex synchronization in nanoseconds.
/// @file thread_synchronization_timing.cpp
/// @brief Measures and prints the times for thread creation and mutex synchronization in nanoseconds.
/// @author Henning Mende
/// @date Nov 22, 2019
/// @copyright Henning Mende
///
/// Compile with posix pthread library:
/// @code
/// g++ thread_related_timing.cpp -pthread
/// @endcode
///
/// This program is free software: you can redistribute it and/or modify it under the terms
/// of the GNU General Public License as published by the Free Software Foundation, either
/// version 3 of the License, or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
/// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/// See the GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License along with this program.
/// If not, see <https://www.gnu.org/licenses/>.
#include <thread>
#include <mutex>
#include <chrono>
#include <iostream>
int main(int argc, char **argv) {
std::mutex mutex;
mutex.lock();
using Clock = std::chrono::high_resolution_clock;
auto tCreateThread1 = Clock::now();
decltype(tCreateThread1) tCreateThread2, tCreateThread3, tMutexSync1,
tMutexSync2, tMutexSync3;
tCreateThread1 = Clock::now();
std::thread myThread([&] {
tCreateThread2 = Clock::now();
mutex.lock();
tMutexSync2 = Clock::now();
});
tCreateThread3 = Clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(2));
std::printf(" between | trigger\n");
std::printf("thread creation: %9ld | %9ld\n",
std::chrono::duration_cast<std::chrono::nanoseconds>(tCreateThread2 - tCreateThread1).count(),
std::chrono::duration_cast<std::chrono::nanoseconds>(tCreateThread3 - tCreateThread1).count());
tMutexSync1 = Clock::now();
mutex.unlock();
tMutexSync3 = Clock::now();
myThread.join();
std::printf("mutex sync: %9ld | %9ld\n",
std::chrono::duration_cast<std::chrono::nanoseconds>(tMutexSync2 - tMutexSync1).count(),
std::chrono::duration_cast<std::chrono::nanoseconds>(tMutexSync3 - tMutexSync1).count());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment