I am using boost::posix_time::ptime to measure my simulation run-time and for something else.
assuimg
boost::posix_time::ptime start, stop;
boost::posix_time::time_duration diff;
start = boost::posix_time::microsec_clock::local_time();
sleep(5);
stop = boost::posix_time::microsec_clock::local_time();
diff = stop - stop;
now
std::cout << to_simple_string( diff ) << std::endl;
return the time in hh:mm:ss.ssssss format and i would like to have the time as well in ss.sssssss.
for doing this, i tried
boost::posix_time::time_duration::sec_type x = diff.total_seconds();
but that gave me the answer in format of ss and seconds() returns Returns normalized number of seconds (0..60).
My question how could i get my simulation time in seconds of the format ss.ssssss?
EDIT
i was able to do:
std::cout << diff.total_seconds() << "." << diff.fractional_seconds() << std::endl;
is there something elegant that could plot ss.sssssss?
total_seconds() returns a long value which is not normalized to 0..60s.
So just do this:
namespace bpt = boost::posix_time;
int main(int , char** )
{
bpt::ptime start, stop;
start = bpt::microsec_clock::local_time();
sleep(62);
stop = bpt::microsec_clock::local_time();
bpt::time_duration dur = stop - start;
long milliseconds = dur.total_milliseconds();
std::cout << milliseconds << std::endl; // 62000
// format output with boost::format
boost::format output("%.2f");
output % (milliseconds/1000.0);
std::cout << output << std::endl; // 62.00
}
// whatever time you have (here 1second)
boost::posix_time::ptime pt = boost::posix_time::from_time_t( 1 );
// subtract 0 == cast to duration
boost::posix_time::time_duration dur = pt - boost::posix_time::from_time_t(0);
// result in ms
uint64_t ms = dur.total_milliseconds();
// result in usec
uint64_t us = dur.total_microseconds();
// result in sec
uint64_t s = dur.total_seconds();
std::cout << "s = " << s << ", ms = " << ms << ", us = " << us << std::endl;
s = 1, ms = 1000, us = 1000000
The most straight-forward way I see is something like this output, the rest of the time computations along the lines of nabulke's post:
#include <iomanip>
double dseconds = dur.total_milliseconds() / 1000. ;
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(3);
std::cout << dseconds << std::endl;
You want to express time in terms of a floating point number, so it's probably best to actually use one and apply the standard stream formatting manipulators.
Related
I try to get the time elapsed between two points in time in milliseconds as integer or in seconds as double.
I'm trying to put constant acceleration of 4m/s² on something. I got this already:
int main() {
double accel = 4, velocity = 0;
auto start = chrono::system_clock::now();
sleep(3);
auto ende = chrono::system_clock::now();
chrono::duration<double> elapsed_seconds = ende - start;
velocity += accel * elapsed_seconds; //This is where I don't know what to put instead of "elapsed_seconds"
cout << "Velocity after " << elapsed_seconds << "s is " << velocity << "m/s" << endl;
return 0;
}
But as you might see it doesn't work. I already found something like
chrono::duration_cast<ms>(elapsed_time);
but I can't get it to work. Do you have any ideas?
It's maybe a little strange to say you "count" a double but elapsed_seconds.count() will return the underlying value.
To get the seconds as a double:
auto seconds = chrono::duration<double>(ende - start);
auto val = seconds.count();
To get milliseconds:
auto ms = chrono::duration_cast<chrono::milliseconds>(ende - start);
auto val = ms.count();
Be careful when using duration_cast, you can lose precision.
I need to convert a boost::posix_time::ptime into a NTP Datestamp according to
RFC 5905 represented by the following structure:
struct NtpDatestamp {
std::int32_t era_number;
std::uint32_t seconds_since_era_epoch;
std::uint64_t fraction_of_second;
};
RFC 5905 states the following:
To convert system time in any format to NTP date and timestamp formats
requires that the number of seconds s from the prime epoch to the system
time be determined. To determine the integer era and timestamp given s,
era = s / 2^(32) and timestamp = s - era * 2^(32),
which works for positive and negative dates. To determine s given the era
and timestamp,
s = era * 2^(32) + timestamp.
Therefore I've tried the following:
const auto system_time = boost::posix_time::time_from_string("1899-12-31 00:00:00.000");
const boost::posix_time::ptime prime_epoch{boost::gregorian::date{1900, 1, 1}};
// Calculate the number of seconds from the prime epoch to the system time.
const boost::posix_time::time_duration time_duration{system_time - prime_epoch};
const std::int64_t s{time_duration.total_seconds()};
const std::int32_t era_number{static_cast<std::int32_t>(s / std::pow(2, 32))};
const std::uint64_t seconds_since_era_epoch{static_cast<std::uint64_t>(s - s / std::pow(2, 32) * std::pow(2, 32))};
// The fraction of a NTP Datestamp is measured in Attoseconds.
const std::uint64_t fraction_of_second{static_cast<std::uint64_t>(time_duration.total_microseconds() * 1e12)};
But that gives incorrect results.
I am completely stumped with this (actually simple) problem at the moment.
Can someone guide me into the correct direction? How can I obtain the era number, era offset and fraction of a NTP datestamp from a boost::posix_time::ptime?
Edit: Either the calculations in RFC 5905 are not accurate enough or I do misinterpret them. Thanks to the comments I've changed the calculation to the following (this time a complete example):
#include <cmath>
#include <cstdint>
#include <iostream>
#include <boost/date_time.hpp>
int main() {
const auto system_time =
boost::posix_time::time_from_string("1899-12-31 00:00:00.000");
const boost::posix_time::ptime prime_epoch{
boost::gregorian::date{1900, 1, 1}};
// Calculate the number of seconds from the prime epoch to the system time.
const boost::posix_time::time_duration time_duration{prime_epoch -
system_time};
// s is correctly determined now.
std::int64_t s{time_duration.total_seconds()};
if (prime_epoch > system_time) {
// boost::posix_time::time_duration does not take the sign into account.
s *= -1;
}
// TODO(wolters): The following calculations do not return the correct
// results, but the RFC 5905 states them
const std::int32_t era{static_cast<std::int32_t>(s / std::pow(2, 32))};
const std::uint64_t timestamp{
static_cast<std::uint64_t>(s - era * std::pow(2, 32))};
// The fraction of a NTP Datestamp is measured in Attoseconds.
// TODO(wolters): `boost::posix_time::ptime` does NOT resolve to attoseconds,
// but doesn't the target format expect the value to be specified as
// attoseconds? Doesn't the following depend on Boost compile options?
const std::uint64_t fraction{
static_cast<std::uint64_t>(time_duration.fractional_seconds())};
std::cout << "s = " << std::dec << s << '\n';
// TODO(wolters): This does still not match the expected results; taken from
// Figure 4 of https://www.ietf.org/rfc/rfc5905.txt
std::cout << "Era (expected: -1) = " << std::dec << era << '\n';
std::cout << "Timestamp (expected: 4294880896) = " << std::dec << timestamp
<< '\n';
std::cout << "Fraction (expected: 0) = " << std::dec << fraction << '\n';
}
s is calculated correctly now, but the other calculations are wrong. I think I do miss something important completely...
It seems that I've figured out the missing pieces by myself. I've implemented the following algorithm in a reusable class ntp::Datestamp and unit tested it with the reference dates of RFC 5905. All tests finally are green. Here is the solution:
#include <cmath>
#include <cstdint>
#include <ctime>
#include <iostream>
#include <boost/date_time.hpp>
static std::time_t to_time(const boost::posix_time::ptime& time) {
static const boost::posix_time::ptime epoch_time{
boost::gregorian::date{1970, 1, 1}};
const boost::posix_time::time_duration diff{time - epoch_time};
return (diff.ticks() / diff.ticks_per_second());
}
int main() {
const auto system_time =
boost::posix_time::time_from_string("1899-12-31 00:00:00.123");
const boost::posix_time::ptime prime_epoch{
boost::gregorian::date{1900, 1, 1}};
// Calculate the number of seconds from the prime epoch to the system time.
std::time_t s{to_time(system_time) - to_time(prime_epoch)};
const std::int32_t era{static_cast<std::int32_t>(std::floor(s / std::pow(2, 32)))};
const std::uint32_t timestamp{
static_cast<std::uint32_t>(s - era * std::pow(2, 32))};
const std::uint64_t fraction{static_cast<std::uint64_t>(
system_time.time_of_day().fractional_seconds())};
std::cout << "s = " << std::dec << s << '\n';
std::cout << "Era (expected: -1) = " << std::dec << era << '\n';
std::cout << "Timestamp (expected: 4294880896) = " << std::dec << timestamp
<< '\n';
std::cout << "Fraction (expected: 123000) = " << std::dec << fraction << '\n';
}
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 have following C code:
uint64_t combine(uint32_t const sec, uint32_t const usec){
return (uint64_t) sec << 32 | usec;
};
uint64_t now3(){
struct timeval tv;
gettimeofday(&tv, NULL);
return combine((uint32_t) tv.tv_sec, (uint32_t) tv.tv_usec);
}
What this do it combine 32 bit timestamp, and 32 bit "something", probably micro/nanoseconds into single 64 bit integer.
I have really hard time to rewrite it with C++11 chrono.
This is what I did so far, but I think this is wrong way to do it.
auto tse = std::chrono::system_clock::now().time_since_epoch();
auto dur = std::chrono::duration_cast<std::chrono::nanoseconds>( tse ).count();
uint64_t time = static_cast<uint64_t>( dur );
Important note - I only care about first 32 bit to be "valid" timestamp.
Second 32 bit "part" can be anything - nano or microseconds - everything is good as long as two sequential calls of this function give me different second "part".
i want seconds in one int, milliseconds in another.
Here is code to do that:
#include <chrono>
#include <iostream>
int
main()
{
auto now = std::chrono::system_clock::now().time_since_epoch();
std::cout << now.count() << '\n';
auto s = std::chrono::duration_cast<std::chrono::seconds>(now);
now -= s;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now);
int si = s.count();
int msi = ms.count();
std::cout << si << '\n';
std::cout << msi << '\n';
}
This just output for me:
1447109182307707
1447109182
307
The C++11 chrono types use only one number to represent a time since a given Epoch, unlike the timeval (or timespec) structure which uses two numbers to precisely represent a time. So with C++11 chrono you don't need the combine() method.
The content of the timestamp returned by now() depends on the clock you use; there are tree clocks, described in http://en.cppreference.com/w/cpp/chrono :
system_clock wall clock time from the system-wide realtime clock
steady_clock monotonic clock that will never be adjusted
high_resolution_clock the clock with the shortest tick period available
If you want successive timestamps to be always different, use the steady clock:
auto t1 = std::chrono::steady_clock::now();
...
auto t2 = std::chrono::steady_clock::now();
assert (t2 > t1);
Edit: answer to comment
#include <iostream>
#include <chrono>
#include <cstdint>
int main()
{
typedef std::chrono::duration< uint32_t, std::ratio<1> > s32_t;
typedef std::chrono::duration< uint32_t, std::milli > ms32_t;
s32_t first_part;
ms32_t second_part;
auto t1 = std::chrono::nanoseconds( 2500000000 ); // 2.5 secs
first_part = std::chrono::duration_cast<s32_t>(t1);
second_part = std::chrono::duration_cast<ms32_t>(t1-first_part);
std::cout << "first part = " << first_part.count() << " s\n"
<< "seconds part = " << second_part.count() << " ms" << std::endl;
auto t2 = std::chrono::nanoseconds( 2800000000 ); // 2.8 secs
first_part = std::chrono::duration_cast<s32_t>(t2);
second_part = std::chrono::duration_cast<ms32_t>(t2-first_part);
std::cout << "first part = " << first_part.count() << " s\n"
<< "seconds part = " << second_part.count() << " ms" << std::endl;
}
Output:
first part = 2 s
seconds part = 500 ms
first part = 2 s
seconds part = 800 ms
I'm looking for a concise solution to output a boost::posix_time::time_duration with a precision of milliseconds: There should be exactly 3 fractional-second digits. The default format produces 6 fractional digits (or none, if they are all 0):
#include <boost/date_time.hpp>
#include <iostream>
int main()
{
// Define some duration in milliseconds:
int64_t start_msecs((((40 * 60) + 3) * 60 + 2) * 1000 + 1);
// The same as time_duration:
boost::posix_time::time_duration start_time =
boost::posix_time::milliseconds(start_msecs);
// No suitable format (for MP4Box chapter starts): ////////////////////
std::cout << "Wrong format: "
<< std::setprecision(3) // <-- No effect!?
<< start_time << std::endl;
// Output: "Wrong format: 40:03:02.001000"
// Required format : 40:03:02.001
return 0;
}
Using facets and some work arounds, I can get the required output. But that solution only disables the parts of the date-time library I can't get configured to my needs and replaces them with a low level implementation:
#include <boost/date_time.hpp>
#include <iostream>
int main()
{
// Define some duration in milliseconds:
int64_t start_msecs((((40 * 60) + 3) * 60 + 2) * 1000 + 1);
// The same as time_duration:
boost::posix_time::time_duration start_time =
boost::posix_time::milliseconds(start_msecs);
// Define output format without fractional seconds:
boost::posix_time::time_facet *output_facet =
new boost::posix_time::time_facet();
output_facet->time_duration_format("%O:%M:%S");
// Imbue cout with format for duration output:
std::cout.imbue(std::locale(std::locale::classic(), output_facet));
// Only the milliseconds:
int64_t msecs_only = start_msecs % 1000;
// Render duration with exactly 3 fractional-second digits: ///////////
std::cout << "Working: "
<< start_time << "."
<< std::setw(3) << std::right << std::setfill('0')
<< msecs_only << std::endl;
// Output: "Working: 40:03:02.001"
return 0;
}
What would be the recommended way to achieve the required output?