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
Related
Here's some code that I found:
std::cout << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;
This prints 1662563612364838407 for me; so it looks like this prints the number of nanoseconds since the UNIX epoch (1970-01-01).
But is this precision guaranteed? I didn't find any indication at https://en.cppreference.com/w/cpp/chrono/system_clock that this value will always be in nanoseconds. Is it possible that this will return e.g. microseconds with another compiler, operating system or hardware?
No it is not guaranteed. You can use the clocks period member alias to get tick period in seconds:
#include <chrono>
#include <iostream>
int main() {
std::cout << std::chrono::system_clock::period::num << " / " << std::chrono::system_clock::period::den;
}
Possible output:
1 / 1000000000
Is it possible that this will return e.g. microseconds with another compiler, operating system or hardware?
Yes, but you can always std::chrono::duration_cast it into a known duration unit. If you want it in seconds for example:
auto dur = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch());
std::cout << dur << '\n';
Possible output:
1662575635s
Pre C++20:
std::cout << dur.count() << '\n';
1662575635
Note: Stay within the chrono domain until it's absolutely necessary to leave it (using .count() etc).
How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?
C++20 introduced a guarantee that time_since_epoch is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time() is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
#include<iostream>
#include<ctime>
int main()
{
std::time_t t = std::time(0); // t is an integer type
std::cout << t << " seconds since 01-Jan-1970\n";
return 0;
}
The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
Windows uses a different epoch and time units: see
Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))
So say I set a time in tm to be 23:00:00
ptm->tm_hour = 23; ptm->tm_min = 0; ptm->tm_sec = 0;
And I want to allow a user to subtract time from this
ptm->tm_hour -= hourinput; ptm->tm_min -= minuteinput; ptm->tm_sec -= secondinput;
If the user subtracts 0 hours, 5 minutes, and 5 seconds, instead of showing up as 22:54:55, it will show up as 23:-5:-5.
I suppose I could do a bunch of if statements to check if ptm is below 0 and account for this, but is there a more efficient way of getting the proper time?
Yes, you can use std::mktime for this. It doesn't just convert a std::tm to a std::time_t, it also fixes the tm if some field went out of range. Consider this example where we take the current time and add 1000 seconds.
#include <iostream>
#include <iomanip> // put_time
#include <ctime>
int main(int argc, char **argv) {
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);
std::cout << "Time: " << std::put_time(&tm, "%c %Z") << std::endl;
tm.tm_sec += 1000; // the seconds are now out of range
//std::cout << "Time in 1000 sec" << std::put_time(&tm, "%c %Z") << std::endl; this would crash!
std::mktime(&tm); // also returns a time_t, but we don't need that here
std::cout << "Time in 1000 sec: " << std::put_time(&tm, "%c %Z") << std::endl;
return 0;
}
My Output:
Time: 01/24/19 09:26:46 W. Europe Standard Time
Time in 1000 sec: 01/24/19 09:43:26 W. Europe Standard Time
As you can see, the time went from 09:26:46 to 09:43:26.
Here's another approach using Howard Hinnant's date library, which is on its way into C++2a.
#include <iostream>
#include "date/date.h"
using namespace std::chrono_literals;
// Time point representing the start of today:
auto today = date::floor<date::days>(std::chrono::system_clock::now());
auto someTp = today + 23h; // Today, at 23h00
auto anotherTp = someTp - 5min - 5s; // ... should be self-explanatory now :)
std::cout << date::format("%b-%d-%Y %T\n", anotherTp);
If you want to expose the manipulation of time points via a user interface, the compile-time constructs 23h, 5min and so on are of course not available. Those literals construct std::chrono::duration objects, so you need a mechanism to turn user input into equivalent instances.
While I realize this is probably one of many identical questions, I can't seem to figure out how to properly use std::chrono. This is the solution I cobbled together.
#include <stdlib.h>
#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
float startTime;
float getCurrentTime();
int main () {
startTime = getCurrentTime();
std::cout << "Start Time: " << startTime << "\n";
while(true) {
std::cout << getCurrentTime() - startTime << "\n";
}
return EXIT_SUCCESS;
}
float getCurrentTime() {
auto now = Time::now();
return std::chrono::duration_cast<ms>(now.time_since_epoch()).count() / 1000;
}
For some reason, this only ever returns integer values as the difference, which increments upwards at rate of 1 per second, but starting from an arbitrary, often negative, value.
What am I doing wrong? Is there a better way of doing this?
Don't escape the chrono type system until you absolutely have to. That means don't use .count() except for I/O or interacting with legacy API.
This translates to: Don't use float as time_point.
Don't bother with high_resolution_clock. This is always a typedef to either system_clock or steady_clock. For more portable code, choose one of the latter.
.
#include <iostream>
#include <chrono>
using Time = std::chrono::steady_clock;
using ms = std::chrono::milliseconds;
To start, you're going to need a duration with a representation of float and the units of seconds. This is how you do that:
using float_sec = std::chrono::duration<float>;
Next you need a time_point which uses Time as the clock, and float_sec as its duration:
using float_time_point = std::chrono::time_point<Time, float_sec>;
Now your getCurrentTime() can just return Time::now(). No fuss, no muss:
float_time_point
getCurrentTime() {
return Time::now();
}
Your main, because it has to do the I/O, is responsible for unpacking the chrono types into scalars so that it can print them:
int main () {
auto startTime = getCurrentTime();
std::cout << "Start Time: " << startTime.time_since_epoch().count() << "\n";
while(true) {
std::cout << (getCurrentTime() - startTime).count() << "\n";
}
}
This program does a similar thing. Hopefully it shows some of the capabilities (and methodology) of std::chrono:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
using namespace std::literals;
namespace chrono = std::chrono;
using clock_type = chrono::high_resolution_clock;
auto start = clock_type::now();
for(;;) {
auto first = clock_type::now();
// note use of literal - this is c++14
std::this_thread::sleep_for(500ms);
// c++11 would be this:
// std::this_thread::sleep_for(chrono::milliseconds(500));
auto last = clock_type::now();
auto interval = last - first;
auto total = last - start;
// integer cast
std::cout << "we just slept for " << chrono::duration_cast<chrono::milliseconds>(interval).count() << "ms\n";
// another integer cast
std::cout << "also known as " << chrono::duration_cast<chrono::nanoseconds>(interval).count() << "ns\n";
// floating point cast
using seconds_fp = chrono::duration<double, chrono::seconds::period>;
std::cout << "which is " << chrono::duration_cast<seconds_fp>(interval).count() << " seconds\n";
std::cout << " total time wasted: " << chrono::duration_cast<chrono::milliseconds>(total).count() << "ms\n";
std::cout << " in seconds: " << chrono::duration_cast<seconds_fp>(total).count() << "s\n";
std::cout << std::endl;
}
return 0;
}
example output:
we just slept for 503ms
also known as 503144616ns
which is 0.503145 seconds
total time wasted: 503ms
in seconds: 0.503145s
we just slept for 500ms
also known as 500799185ns
which is 0.500799 seconds
total time wasted: 1004ms
in seconds: 1.00405s
we just slept for 505ms
also known as 505114589ns
which is 0.505115 seconds
total time wasted: 1509ms
in seconds: 1.50923s
we just slept for 502ms
also known as 502478275ns
which is 0.502478 seconds
total time wasted: 2011ms
in seconds: 2.01183s
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);
}
}