I am currently working on a project that requires me to store a vector of future so I can measure the execution time accurately, however when I call
posterTotal += posterDurationFutures[i].get();
the program just crashes with no error message. Wrapping the line in a try/catch block also does not work, as it doesn't seem to be throwing an exception.
Here is my code (please bare in mind that this is a work in progress):
#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
#include <future>
#include <queue>
#include "TCPClient.h"
#include "ThreadPool.h"
#include "RequestGenerator.h"
#include "ResponseVerifier.h"
#include "Storage.h"
#define DEFAULT_PORT 12345
double readRequest(TCPClient client, int threadIndex, double timeDurationSecs);
double postRequest(TCPClient client, int threadIndex, double timeDurationSecs);
string sendViaClient(TCPClient client, string request);
unsigned int readRequests = 0;
unsigned int postRequests = 0;
Storage* db = new Storage();
ResponseVerifier* responseVerifier = new ResponseVerifier();
RequestGenerator* requestGenerator = new RequestGenerator();
int main(int argc, char **argv)
{
// Default parameters
unsigned int posterCount = 5;
unsigned int readerCount = 0;
double timeDurationSecs = 10;
bool throttle = false;
string serverIp = "127.0.0.1";
// Validate the parameters
if (argc != 6) {
std::cout << "\nUsage (required parameters): server_IP number_of_poster_threads number_of_reader_threads time_duration throttle(0|1)\n\n";
std::cout << "server_IP - IP of the server\n";
std::cout << "number_of_poster_threads - number of threads performing POST operations\n";
std::cout << "number_of_reader_threads - number of threads performing READ operations\n";
std::cout << "time_duration - duration of test execution in seconds\n";
std::cout << "throttle(0|1) - 0: do not throttle message speed\n";
std::cout << "\t\t1: throttle message speed\n\n";
std::cout << "\nDefault Parameters:\n";
std::cout << "\tserver_IP - " << serverIp << "\n";
std::cout << "\tnumber_of_poster_threads - " << posterCount << "\n";
std::cout << "\tnumber_of_reader_threads - " << readerCount << "\n";
std::cout << "\ttime_duration - " << timeDurationSecs << "s\n";
std::cout << "\tthrottle - " << (throttle ? "true" : "false") << "\n\n";
std::cout << "Enter dev mode using default parameters?\n";
system("pause");
}
else
{
serverIp = argv[1];
posterCount = (int)argv[2];
readerCount = (int)argv[3];
timeDurationSecs = (int)argv[4];
throttle = (int)argv[5];
}
//std::queue<future<bool>> posterVerificationQueue;
//std::queue<bool> readerVerificationQueue;
ThreadPool posterPool(posterCount);
//ThreadPool readerPool(readerCount);
//vector<thread> posterThreads;
//vector<thread> readerThreads;
vector<future<double>> posterDurationFutures;
TCPClient client(serverIp, DEFAULT_PORT);
client.OpenConnection();
chrono::high_resolution_clock::time_point endTime;
chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();
for (int i = 0; i < posterCount; i++)
{
//posterThreads.emplace_back(postRequest, client, i, timeDurationSecs);
//std::future<double> durationFut = std::async(std::launch::async, postRequest, client, i, timeDurationSecs);
//posterDurationFutures.push_back(async(launch::async, postRequest, client, i, timeDurationSecs));
posterDurationFutures.push_back(posterPool.enqueue(postRequest, client, i, timeDurationSecs));
}
double posterTotal = 0;
for (int i = 0; i < posterDurationFutures.size(); i++)
{
bool valid = posterDurationFutures[i].valid();
//posterDurationFutures[i].wait();
posterTotal += posterDurationFutures[i].get();
}
cout << posterTotal;
for (int i = 0; i < readerCount; i++)
{
//readerThreads.emplace_back();
}
client.CloseConnection();
delete db;
delete responseVerifier;
delete requestGenerator;
system("pause");
return 0;
}
inline string sendViaClient(TCPClient client, string request)
{
return client.send(request);
}
double postRequest(TCPClient client, int threadIndex, double timeDurationSecs)
{
int threadPostCount = 0;
chrono::high_resolution_clock::time_point endTime;
chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();
do
{
string request = requestGenerator->generateWriteRequest();
string response = client.send(request);
bool isValidResponse = db->addPosterValue(request, response);
endTime = chrono::high_resolution_clock::now();
postRequests++;
threadPostCount++;
} while (chrono::duration_cast<chrono::duration<double>>(endTime - startTime).count() < timeDurationSecs);
double totalRunTime = (endTime - startTime).count();
double posterRequestsPerSecond = threadPostCount / totalRunTime;
std::cout << "Thread: " << threadIndex << endl;
std::cout << "Average post requests per second: " << posterRequestsPerSecond << endl;
return totalRunTime;
}
double readRequest(TCPClient client, int threadIndex, double timeDurationSecs)
{
return 0.0;
}
I need to convert seconds in to hh:mm:ss.milliseconds and I need that this format must be respected. I mean that hours, minutes and seconds must have 2 digits and milliseconds 3 digits.
For example, if seconds = 3907.1 I would to obtain 01:05:07.100
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdio.h>
#include <sstream>
#include <math.h>
using namespace std;
int main()
{
double sec_tot = 3907.1;
double hour = sec_tot/3600; // seconds in hours
double hour_int;
double hour_fra = modf(hour, &hour_int );//split integer and decimal part of hours
double minutes = hour_fra*60; // dacimal hours in minutes
double minutes_int;
double minutes_fra = modf(minutes, &minutes_int); // split integer and decimal part of minutes
double seconds = minutes_fra*60; // decimal minutes in seconds
stringstream ss;
ss << ("%02lf", hour_int) << ":" << ("%02lf", minutes_int) << ":" << ("%02lf", seconds);
string time_obs_def = ss.str();
cout << time_obs_def << endl;
return 0;
}
but the output is 1:5:7.1
Thank you.
Nowadays you should probably use the chrono duration std::chrono::milliseconds for such a task, but if you'd like make our own type to support formatting, something like this should do it:
#include <iomanip> // std::setw & std::setfill
#include <iostream>
// your own type
struct seconds_t {
double value;
};
// ostream operator for your type:
std::ostream& operator<<(std::ostream& os, const seconds_t& v) {
// convert to milliseconds
int ms = static_cast<int>(v.value * 1000.);
int h = ms / (1000 * 60 * 60);
ms -= h * (1000 * 60 * 60);
int m = ms / (1000 * 60);
ms -= m * (1000 * 60);
int s = ms / 1000;
ms -= s * 1000;
return os << std::setfill('0') << std::setw(2) << h << ':' << std::setw(2) << m
<< ':' << std::setw(2) << s << '.' << std::setw(3) << ms;
}
int main() {
seconds_t m{3907.1};
std::cout << m << "\n";
}
Coming in C++20:
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int
main()
{
double sec_tot = 3907.1;
cout << format("{:%T}\n", round<milliseconds>(duration<double>{sec_tot}));
}
printf style format specifiers do not work. You will need to use the stream manipulators to set the width and fill character.
ss << std:setw(2) << std::setfill('0') << hour_int;
This will also add a leading zero to enforce hh:mm:ss format.
If hh is 00, returns only mm:ss.
ms are left out from this example, but easy to add.
#include <iostream>
std::string convertSecondsToHHMMSS (int value) {
std::string result;
// compute h, m, s
std::string h = std::to_string(value / 3600);
std::string m = std::to_string((value % 3600) / 60);
std::string s = std::to_string(value % 60);
// add leading zero if needed
std::string hh = std::string(2 - h.length(), '0') + h;
std::string mm = std::string(2 - m.length(), '0') + m;
std::string ss = std::string(2 - s.length(), '0') + s;
// return mm:ss if hh is 00
if (hh.compare("00") != 0) {
result = hh + ':' + mm + ":" + ss;
}
else {
result = mm + ":" + ss;
}
return result;
}
int main() {
std::cout << convertSecondsToHHMMSS(3601) << "\n";
std::cout << convertSecondsToHHMMSS(1111) << "\n";
std::cout << convertSecondsToHHMMSS(60) << "\n";
std::cout << convertSecondsToHHMMSS(12) << "\n";
std::cout << convertSecondsToHHMMSS(0) << "\n";
}
I need to get the current time (hour,minutes and seconds) and add 30 minutes. In final i need to save the result to an integer variable.
How it's possible to do?
My code at the moment:
int main()
{
time_t currentTime;
struct tm *localTime;
time( ¤tTime );
localTime = localtime( ¤tTime );
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
std::cout << "Execute at: " << Hour << ":" << Min << ":" << Sec << std::endl;
return 0;
}
Thanks
you can do the following to get time 30 minutes ahead of local time:
time_t currentTime;
struct tm *localTime;
time( ¤tTime );
currentTime += 1*30*60;
localTime= localtime(&utc);
The localTime structure now has 30 minutes ahead of current local time.You can get the values in integers as you were doing before.
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
In case you need string out of it,you can do
std::string strAheadTime = asctime(localTime);
You can achieve the same like this -
#include <iostream>
#include <ctime>
int main()
{
time_t currentTime;
struct tm *localTime;
time( ¤tTime ); // Get the current time
localTime = localtime( ¤tTime ); // Convert the current time to the local time
int Hour = localTime->tm_hour;
int Min = localTime->tm_min;
int Sec = localTime->tm_sec;
std::cout << "The current time is : " << Hour << ":" << Min << ":" << Sec << std::endl;
//increase local time by 30 minutes and adjust minutes and hour.
int IncMin = Min + 30;
if(IncMin >= 60){
int res = IncMin/60;
int newMin = IncMin % 60;
Hour += res;
if(Hour > 23){
Hour = 00;
}
std::cout << "The updated time is : " << Hour << ":" << newMin << ":" << Sec << std::endl;
}
return 0;
}
#include <iostream>
#include <sys/time.h>
static long elapsedTime(struct timeval &then)
{
struct timeval when;
gettimeofday(&when, NULL);
long result = (when.tv_sec - then.tv_sec) * 1000;
result += (when.tv_usec - then.tv_usec) / 1000;
then = when;
return (result > 0) ? result : 0;
}
int main()
{
struct timeval now;
gettimeofday(&now, NULL);
long elapsed, everyMinute = 0;
while (true) {
elapsed = elapsedTime(now);
everyMinute += elapsed;
if (everyMinute % 1000 == 0)
std::cout << "After: " << everyMinute << std::endl;
}
return 0;
}
I am trying to get this loop to print every minute but gettimeofday gives me unexpected behavior. For example this line std::cout << "Before: " << everyMinute << std::endl; will cause the if to work but without it I just get zeros: here is snippet but it is better to plug into your own compiler.
I am testing some algorithms and timing them. I would like to know how to abort the function while its running if it runs for longer than 60 seconds. Here's what I'm working with:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <random>
#include <algorithm>
using namespace std;
bool isUnique(const vector<int>& arr, int start, int end) {
if (start >= end) return true;
if (!isUnique(arr, start, end - 1))
return false;
if (!isUnique(arr, start + 1, end))
return false;
return (arr[start] != arr[end]);
}
bool isUniqueLoop(const vector<int>& arr, int start, int end) {
if (start >= end) return true;
for (int i = start; i < end; i++)
for (int j = i + 1; j <= end; j++)
if (arr[i] == arr[j])return false;
return true;
}
bool isUniqueSort(const vector<int>& arr, int start, int end) {
if (start <= end) return true;
vector<int> buf(arr);
sort(buf.begin() + start, buf.begin() + end);
for (int i = start; i < end; i++)
if (buf[i] == buf[i + 1]) return false;
return true;
}
int main() {
int max = 0;
cout << "Enter a number for the Max range: ";
cin >> max;
default_random_engine randGen(time(0));
uniform_int_distribution<int> randNum(0, max);
int i;
int j;
int n = randNum(randGen);
int m = n;
vector<int> myVect;
for (i = 0; i <= m; i++) {
myVect.push_back(randNum(randGen));
//cout << myVect[i] << endl;
}
cout << "Recursive Algorithm Test... " << endl;
cout << endl;
// recursive algorithm
clock_t start = clock();
isUnique(myVect, 0, n);
if (isUnique(myVect, 0, n) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique! " << endl;
}
clock_t end = clock();
double time = (double)(end - start) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU Time used for this algorithm: " << time << " ms" << endl;
if (time > 60000) {
cout << "This function takes too long! " << endl;
}
cout << "------------------------------------" << endl;
cout << "Iterative Algorithm Test... " << endl;
cout << endl;
// iterative algorithm
clock_t start2 = clock();
isUniqueLoop(myVect, 0, n);
if (isUniqueLoop(myVect, 0, n) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique! " << endl;
}
clock_t end2 = clock();
double time2 = (double)(end2 - start2) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU time used for this algorithm: " << time2 << " ms. " << endl;
if (time2 > 60000) {
cout << "This function takes too long! " << endl;
}
cout << "------------------------------------" << endl;
cout << "Sort Algorithm Test... " << endl;
cout << endl;
// sort algorithm
clock_t start3 = clock();
isUniqueSort(myVect, 0, n);
if (isUniqueSort(myVect, 0, n) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique " << endl;
}
clock_t end3 = clock();
double time3 = (double)(end3 - start3) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU time used for this algorithm: " << time3 << " ms. " << endl;
if (time3 > 60000) {
cout << "This function takes too long! " << endl;
}
cout << endl;
system("pause");
return 0;
}
everything works fine except the fact that I want it to quit the function isUnique(myVect, 0, m) if it lasts longer than 60 seconds....Any suggestions?
When you have an exceptional circumstance (like a timeout) you can throw an exception. In your case what kind of exceptions is up to you. Exceptions work well when you want to exit a many levels deep call tree without having to check every function individually for an exit return code. In the example below I am throwing a string as an exception:
Edit
To prevent doing the time calculations way too often here is an attempt to limit how often they are done. This is by no means scientific, but on my box it gives a reasonable result. If you have a better way let me know.
#include <iostream>
#include <vector>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <random>
#include <algorithm>
bool isUnique(const std::vector<int>& arr, int start, int end, clock_t clock_start,
unsigned long & iterations, unsigned long timecheck) {
if (++iterations > timecheck) {
iterations = 0;
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) * 1000.0 / CLOCKS_PER_SEC;
if (time > 60000) throw "This function takes too long!";
else std::cout << time << " ms elapsed..." << std::endl;
}
if (start >= end) return true;
if (!isUnique(arr, start, end - 1, clock_start, iterations, timecheck))
return false;
if (!isUnique(arr, start + 1, end, clock_start, iterations, timecheck))
return false;
return (arr[start] != arr[end]);
}
bool isUniqueLoop(const std::vector<int>& arr, int start, int end, clock_t clock_start,
unsigned long & iterations, unsigned long timecheck) {
if (start >= end) return true;
for (int i = start; i < end; i++) {
for (int j = i + 1; j <= end; j++) {
if (++iterations > timecheck) {
iterations = 0;
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) * 1000.0 / CLOCKS_PER_SEC;
if (time > 60000) throw "This function takes too long!";
else std::cout << time << " ms elapsed..." << std::endl;
}
if (arr[i] == arr[j])return false;
}
}
return true;
}
bool isUniqueSort(const std::vector<int>& arr, int start, int end, clock_t clock_start,
unsigned long & iterations, unsigned long timecheck) {
if (start <= end) return true;
std::vector<int> buf(arr);
sort(buf.begin() + start, buf.begin() + end);
for (int i = start; i < end; i++) {
if (++iterations > timecheck) {
iterations = 0;
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) * 1000.0 / CLOCKS_PER_SEC;
if (time > 60000) throw "This function takes too long!";
else std::cout << time << " ms elapsed..." << std::endl;
}
if (buf[i] == buf[i + 1]) return false;
}
return true;
}
unsigned long calculate_timecheck() {
// since we want to limit the functions to 60 seconds we need to check how
// long they have been running but we don't want to do that all the time
// so we should only check so often - here is an attemopt to figure out how often
unsigned long upperlimit = 1;
volatile unsigned long i;
clock_t start, current;
double time;
do {
if (upperlimit > ULONG_MAX/2) return ULONG_MAX-1;
upperlimit *= 2;
start = clock();
for (i = 0; i < upperlimit*100000; i++);
current = clock();
time = (double)(current - start) * 1000.0 / CLOCKS_PER_SEC;
std::cout << upperlimit*100000 << " iterations took " << time << " ms." << std::endl;
} while (time<500);
return upperlimit*100000;
}
int main() {
int max = 0;
std::cout << "Enter a number for the Max range: ";
std::cin >> max;
std::default_random_engine randGen(time(0));
std::uniform_int_distribution<int> randNum(0, max);
int n = randNum(randGen);
int m = n;
std::vector<int> myVect;
for (int i = 0; i <= m; i++) {
myVect.push_back(randNum(randGen));
//std::cout << myVect[i] << std::endl;
}
std::cout << "Calculating timeout... " << std::endl;
std::cout << std::endl;
unsigned long timecheck = calculate_timecheck();
std::cout << "Will check for timeout every " << timecheck << " iterations..." << std::endl;
std::cout << std::endl;
std::cout << "------------------------------------" << std::endl;
// recursive algorithm
try {
std::cout << "Recursive Algorithm Test... " << std::endl;
std::cout << std::endl;
clock_t start = clock();
unsigned long iterations = 0;
// isUnique(myVect, 0, n, start, iterations, timecheck);
if (isUnique(myVect, 0, n, start, iterations, timecheck) == true) {
std::cout << "The Vector is Unique! " << std::endl;
}
else {
std::cout << "The Vector is not Unique! " << std::endl;
}
clock_t end = clock();
double time = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;
std::cout << "CPU Time used for this algorithm: " << time << " ms." << std::endl;
} catch (const char *err) {
std::cout << err << std::endl;
}
std::cout << "------------------------------------" << std::endl;
// iterative algorithm
try {
std::cout << "Iterative Algorithm Test... " << std::endl;
std::cout << std::endl;
clock_t start = clock();
unsigned long iterations = 0;
// isUniqueLoop(myVect, 0, n, start, iterations, timecheck);
if (isUniqueLoop(myVect, 0, n, start, iterations, timecheck) == true) {
std::cout << "The Vector is Unique! " << std::endl;
}
else {
std::cout << "The Vector is not Unique! " << std::endl;
}
clock_t end = clock();
double time = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;
std::cout << "CPU time used for this algorithm: " << time << " ms." << std::endl;
} catch (const char *err) {
std::cout << err << std::endl;
}
std::cout << "------------------------------------" << std::endl;
// sort algorithm
try {
std::cout << "Sort Algorithm Test... " << std::endl;
std::cout << std::endl;
clock_t start = clock();
unsigned long iterations = 0;
// isUniqueSort(myVect, 0, n, start, iterations, timecheck);
if (isUniqueSort(myVect, 0, n, start, iterations, timecheck) == true) {
std::cout << "The Vector is Unique! " << std::endl;
}
else {
std::cout << "The Vector is not Unique " << std::endl;
}
clock_t end = clock();
double time = (double)(end - start) * 1000.0 / CLOCKS_PER_SEC;
std::cout << "CPU time used for this algorithm: " << time << " ms." << std::endl;
} catch (const char *err) {
std::cout << err << std::endl;
}
std::cout << std::endl;
system("pause");
return 0;
}
Original:
#include <iostream>
#include <vector>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <random>
#include <algorithm>
using namespace std;
bool isUnique(const vector<int>& arr, int start, int end, clock_t clock_start) {
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) / CLOCKS_PER_SEC * 1000.0;
if (time > 60000) throw "This function takes too long!";
if (start >= end) return true;
if (!isUnique(arr, start, end - 1, clock_start))
return false;
if (!isUnique(arr, start + 1, end, clock_start))
return false;
return (arr[start] != arr[end]);
}
bool isUniqueLoop(const vector<int>& arr, int start, int end, clock_t clock_start) {
if (start >= end) return true;
for (int i = start; i < end; i++) {
for (int j = i + 1; j <= end; j++) {
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) / CLOCKS_PER_SEC * 1000.0;
if (time > 60000) throw "This function takes too long!";
if (arr[i] == arr[j])return false;
}
}
return true;
}
bool isUniqueSort(const vector<int>& arr, int start, int end, clock_t clock_start) {
if (start <= end) return true;
vector<int> buf(arr);
sort(buf.begin() + start, buf.begin() + end);
for (int i = start; i < end; i++) {
clock_t clock_current = clock();
double time = (double)(clock_current - clock_start) / CLOCKS_PER_SEC * 1000.0;
if (time > 60000) throw "This function takes too long!";
if (buf[i] == buf[i + 1]) return false;
}
return true;
}
int main() {
int max = 0;
cout << "Enter a number for the Max range: ";
cin >> max;
default_random_engine randGen(time(0));
uniform_int_distribution<int> randNum(0, max);
int i;
int j;
int n = randNum(randGen);
int m = n;
vector<int> myVect;
for (i = 0; i <= m; i++) {
myVect.push_back(randNum(randGen));
//cout << myVect[i] << endl;
}
try {
cout << "Recursive Algorithm Test... " << endl;
cout << endl;
// recursive algorithm
clock_t start = clock();
isUnique(myVect, 0, n, start);
if (isUnique(myVect, 0, n, start) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique! " << endl;
}
clock_t end = clock();
double time = (double)(end - start) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU Time used for this algorithm: " << time << " ms" << endl;
} catch (const char *err) {
cout << err << endl;
}
cout << "------------------------------------" << endl;
try {
cout << "Iterative Algorithm Test... " << endl;
cout << endl;
// iterative algorithm
clock_t start2 = clock();
isUniqueLoop(myVect, 0, n, start2);
if (isUniqueLoop(myVect, 0, n, start2) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique! " << endl;
}
clock_t end2 = clock();
double time2 = (double)(end2 - start2) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU time used for this algorithm: " << time2 << " ms. " << endl;
} catch (const char *err) {
cout << err << endl;
}
cout << "------------------------------------" << endl;
try {
cout << "Sort Algorithm Test... " << endl;
cout << endl;
// sort algorithm
clock_t start3 = clock();
isUniqueSort(myVect, 0, n, start3);
if (isUniqueSort(myVect, 0, n, start3) == true) {
cout << "The Vector is Unique! " << endl;
}
else {
cout << "The Vector is not Unique " << endl;
}
clock_t end3 = clock();
double time3 = (double)(end3 - start3) / CLOCKS_PER_SEC * 1000.0;
cout << "CPU time used for this algorithm: " << time3 << " ms. " << endl;
} catch (const char *err) {
cout << err << endl;
}
cout << endl;
system("pause");
return 0;
}