In C++, with this:
std::time_t first = time(NULL);
/* .. code .. */
std::time_t second = time(NULL);
std::cout << "Seg : " << difftime(second,first) << std::endl;
I can determine my program's execution duration.
Can I determine its memory consumption at different points through the program?
Not easily.
Related
My question is about the difference of the elapsed time according to the point.
For finding the largest portion of the total elapsed time when executing in my code, I used clock function.
source : calculating time elapsed in C++
First, I put the clock function at the start and end of the main function.
(Actually, there are some declaration of variables but I deleted them for readability of my questions). Then I think I will be able to measure the total elapsed time.
int main(){
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
const auto before = clock::now();
...
std::cin >> a >> b;
lgstCommSubStr findingLCSS(a,b,numberofHT,cardi,SubsA);
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s in main function" << std::endl;
return 0;
}
Second, I put the clock function at the class findingLCSS. This class is for finding longest common sub-string between two string. It is the class that actually do my algorithm. I write the code for finding it in its constructor. Therefore, when making this class, it returns longest common sub-string information. I think this elapsed time will be the actual algorithm running time.
public:
lgstCommSubStr(string a, string b, int numHT, int m, vector <int> ** SA):
strA(a), strB(b), hashTsize(numHT), SubstringsA(SA),
primeNs(numHT), xs(numHT),
A_hashValues(numHT), B_hashValues(numHT),
av(numHT), bv(numHT), cardi(m)
{
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
const auto before = clock::now();
...
answer ans=binarySearch(a,b, numHT);
std::cout << ans.i << " " << ans.j << " " << ans.length << "\n";
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s in the class" << std::endl;
}
The output is as below.
tool coolbox
1 1 3
It took 0.002992s in inner class
It took 4.13945s in main function
It means 'tool' and 'coolbox' have a substring 'ool'
But I am confused that there is a big difference between two times.
Because the first time is total time and the second time is algorithm running time, I have to think its difference time is the elapsed time for declaration variables.
But it looks weird because I think declaration variables time is short.
Is there a mistake in measuring the elapsed time?
Please give me a hint for troubleshoot. Thank you for reading!
Taking a snapshot of the time before std::cin >> a >> b; leads to an inaccurate measurement as you're likely starting the clock before you type in the values for a and b. Generally you want to put your timing as close as possible to the thing you're actually measuring.
I'm trying to figure out how to time the execution of part of my program, but when I use the following code, all I ever get back is 0. I know that can't be right. The code I'm timing recursively implements mergesort of a large array of ints. How do I get the time it takes to execute the program in milliseconds?
//opening input file and storing contents into array
index = inputFileFunction(inputArray);
clock_t time = clock();//start the clock
//this is what needs to be timed
newRecursive.mergeSort(inputArray, 0, index - 1);
//getting the difference
time = clock() - time;
double ms = double(time) / CLOCKS_PER_SEC * 1000;
std::cout << "\nTime took to execute: " << std::setprecision(9) << ms << std::endl;
You can use the chrono library in C++11. Here's how you can modify your code:
#include <chrono>
//...
auto start = std::chrono::steady_clock::now();
// do whatever you're timing
auto end = std::chrono::steady_clock::now();
auto durationMS = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "\n Time took " << durationMS.count() << " ms" << std::endl;
If you're developing on OSX, this blog post from Apple may be useful. It contains code snippets that should give you the timing resolution you need.
I'm printing events in a multi-thread environment the console is a static mutex shared by all the threads.
The problem is randomly every hundred or thousand events the time I get is local time and not UTC.
I have seen this error just in Linux machines (build with g++) but not in Windows (build VC++). I have no clue where I could start, any idea?
void Publish(std::string source, std::string topic, std::string msg) NOEXCEPT {
console.lock();
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
char buf[50];
strftime(buf, sizeof (buf), "%Y-%m-%dT%H:%M:%S+00:00", gmtime(&now));
cout << buf << " " << source << " " << topic << " " << msg << endl;
cout.flush();
console.unlock();
}
struct tm * gmtime (const time_t * timer);
Converts time_t to tm as UTC time. This call uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed as a UTC time (i.e., the time at the GMT timezone).
This must be working correctly.
However, not sure about this:
std::time_t now = std::chrono::high_resolution_clock::to_time_t(*localTime);
Is your *localtime giving the current time accurately under multithreaded situation? Is it a shared variable?
Instead could you use the following:
std::time_t now = time(0);
I'm looking for a way to save the time in a HH::MM::SS fashion in C++. I saw here that they are many solutions and after a little research I opted for time and localtime. However, it seems like the localtime function is a little tricky, since it says:
All calls to localtime and gmtime use the same static structure, so
each call overwrites the results of the previous call.
The problem that this causes is shown in the next snippet of code:
#include <ctime>
#include <iostream>
using namespace std;
int main() {
time_t t1 = time(0); // get time now
struct tm * now = localtime( & t1 );
std::cout << t1 << std::endl;
sleep(2);
time_t t2 = time(0); // get time now
struct tm * now2 = localtime( & t2 );
std::cout << t2 << std::endl;
cout << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday << ", "
<< now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec
<< endl;
cout << (now2->tm_year + 1900) << '-'
<< (now2->tm_mon + 1) << '-'
<< now2->tm_mday << ", "
<< now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec
<< endl;
}
A typical output for this is:
1320655946
1320655948
2011-11-7, 9:52:28
2011-11-7, 9:52:28
So as you can see, the time_t timestamps are correct, but the localtime messes everything up.
My question is: how do I convert a timestamp ot type time_t into a human-readable time?
If you are worried about reentrancy in localtime and gmtime, there is localtime_r and gmtime_r which can handle multiple calls.
When it comes to formatting the time to your liking, check the function strftime.
the localtime() call stores the results in an internal buffer.
Every time you call it you overwrite the buffer.
An alternative solution would be to make a copy of the buffer.
time_t t1 = time(0); // get time now
struct tm* now = localtime( & t1 ); // convert to local time
struct tm copy = *now; // make a local copy.
// ^^^ notice no star.
But note: The only time you should be converting to local time is when you display the value. At all other times you should just keep the time as UTC (for storage and manipulation). Since you are only converting the objects for display convert then print immediately and then things will not go wrong.
localtime has what is best considered a legacy interface. It can't be
used in multithreaded code, for example. In a multithreaded
environment, you can use localtime_r under Posix or localtime_s
under Windows. Otherwise, all you have to do is save the results:
tm then = *localtime( &t1 );
// ...
tm now = *localtime( &t2 );
It would probably be more idiomatic, however, to only call localtime
immediately before formatting the output, e.g.:
std::string
timestampToString( time_t timeAndDate )
{
char results[100];
if ( strftime( results, sizeof( results ), "%Y-%m-%d, %H:%M:%S",
localtime( &timeAndDate) ) == 0 ) {
assert( 0 );
}
return results;
}
and then writing:
std::cout << formatTime( t1 ) << std::endl;
(You could also create a more generic formatting function, which took
the format as an argument.)
You can run continuous clock using following code. It works nicely.
#include<iostream>
#include <Windows.h>
#include<ctime>
using namespace std;
void main() {
while(true) {
system("cls"); //to clear screen
time_t tim;
time(&tim);
cout << ctime(&tim);
Sleep(1);
}
}
The following piece of code is used to print the time in the logs:
#define PRINTTIME() struct tm * tmptime;
time_t tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";
Is there any way to add milliseconds to this?
To have millisecond precision you have to use system calls specific to your OS.
In Linux you can use
#include <sys/time.h>
timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision
timeval has microsecond precision.
In Windows you can use:
#include <Windows.h>
SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs
Of course you can use Boost to do that for you :)
//C++11 Style:
cout << "Time in Milliseconds =" <<
chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count()
<< std::endl;
cout << "Time in MicroSeconds=" <<
chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count()
<< std::endl;
You need a timer with a higher resolution in order to capture milliseconds. Try this:
int cloc = clock();
//do something that takes a few milliseconds
cout << (clock() - cloc) << endl;
This is of course dependent on your OS.
The high resolution timers are usually gettimeofday on Linux style platforms and QueryPerformanceCounter on Windows.
You should be aware that timing the duration of a single operation (even with a high resolution timer) will not yield accurate results. There are too many random factors at play. To get reliable timing information, you should run the task to be timed in a loop and compute the average task time. For this type of timing, the clock() function should be sufficient.
If you don't want to use any OS-specific code, you can use the ACE package which supplies the ACE_OS::gettimeofday function for most standard operating systems.
For example:
ACE_Time_Value startTime = ACE_OS::gettimeofday();
do_something();
ACE_Time_Value endTime = ACE_OS::gettimeofday();
cout << "Elapsed time: " << (endTime.sec() - startTime.sec()) << " seconds and " << double(endTime.usec() - startTime.usec()) / 1000 << " milliseconds." << endl;
This code will work regardless of your OS (as long as ACE supports this OS).
In Ubuntu 16.04 this worked for me...
const std::string currentDateTime() {
char fmt[64], buf[64];
struct timeval tv;
struct tm *tm;
gettimeofday(&tv, NULL);
tm = localtime(&tv.tv_sec);
strftime(fmt, sizeof fmt, "%Y-%m-%d %H:%M:%S.%%06u", tm);
snprintf(buf, sizeof buf, fmt, tv.tv_usec);
return buf;
}
Then, with...
std::cout << currentDateTime();
I get...
2016-12-29 11:09:55.331008
New answer for old question using C++11 or C++14 and this free, open-source library:
#include "tz.h"
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto now = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
cout << format("%e/%m/%Y %T", now) << '\n';
}
This just output for me:
16/01/2017 15:34:32.167
which is my current local date and time to millisecond precision. By eliminating the floor<milliseconds>() you will automatically get whatever precision your system_clock has.
If you wanted the result as a UTC timestamp instead of a local timestamp, it is even easier:
auto now = floor<milliseconds>(system_clock::now());
cout << format("%e/%m/%Y %T", now) << '\n';
And if you want a UTC timestamp and you aren't picky about the precision or the format, you can just:
cout << system_clock::now() << '\n';
which just output for me:
2017-01-16 20:42:11.267245