From fa6ba653d73bc04978a38150ca60b45b47a8f0a2 Mon Sep 17 00:00:00 2001 From: Mike Smith <grimbough@gmail.com> Date: Fri, 4 May 2018 17:16:01 +0200 Subject: [PATCH] add timer to c program --- exercises/hpc_example.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/exercises/hpc_example.cpp b/exercises/hpc_example.cpp index e923b2f..8357d0f 100644 --- a/exercises/hpc_example.cpp +++ b/exercises/hpc_example.cpp @@ -6,6 +6,7 @@ #include <string.h> #include <unistd.h> #include <limits.h> +#include <time.h> #include <iostream> // std::cout, std::endl #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds @@ -18,15 +19,15 @@ int main(int argc,char* argv[]) std::vector <std::string> sources; int *a; size_t mem = 0; - int time = 10; + int waittime = 10; char hostname[HOST_NAME_MAX]; - + time_t t1, t2; for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "-t") { if (i + 1 < argc) { // Make sure we aren't at the end of argv! std::stringstream ss1(argv[++i]); - if (!(ss1 >> time)) + if (!(ss1 >> waittime)) std::cerr << "Invalid number " << argv[i] << '\n'; } else { // Uh-oh, there was no argument to the destination option. std::cerr << "-t option requires one argument." << std::endl; @@ -46,19 +47,23 @@ int main(int argc,char* argv[]) } } + time(&t1); + int result = gethostname(hostname, HOST_NAME_MAX); std::string hostname2 = hostname; std::cout << "Current host is: " + hostname2 << std::endl; - std::cout << "Wait time is: " << time << " seconds" << std::endl; + std::cout << "Wait time is: " << waittime << " seconds" << std::endl; std::cout << "Memory usage is: " << mem << "MB" << std::endl; long int l = mem * 1024 * 1024; a = (int*)calloc(mem, 1024 * 1024); memset(a, 0, mem * 1024 * 1024); - std::this_thread::sleep_for (std::chrono::seconds(time)); + std::this_thread::sleep_for (std::chrono::seconds(waittime)); free(a); + time(&t2); + std::cout << "Actually running time: " << difftime(t2, t1) << " seconds" << std::endl; return 0; } -- GitLab