Benjamin Larsen
Benjamin Larsen

Reputation: 590

Timestamp difference with two decimals c++

I have to timestamps (in µs), which are stored as a uint64_t. My goal is to be able to get the difference between these timestamps in ms, as a float with 2 decimals.

Fx I'd like the result to be 6.520000 ms. Though I can't seem to get them to cast correctly.

I've tried the following without any luck:

uint64_t diffus = ms.getT1 - ms.getT2
float diff = static_cast<float>(diffus);
float diffMS = diff / 1000;
std::cout << diffMS << " ms" << std::endl;

I know this wont make the float only two decimals, but I can't even get that to work. I seem to get the same result all the time, even though I vary T1 and T2 with

srand(time(NULL));
usleep((rand() % 25) * 1000);

The output keeps being:

1.84467e+16 ms
1.84467e+16 ms
1.84467e+16 ms
1.84467e+16 ms

What is happening, and what can I do? :-)

Best regards.

Upvotes: 0

Views: 482

Answers (2)

user6424206
user6424206

Reputation:

I made the assumption that ms.getT1 and ms.getT2 indicated that T1 was earlier in time than T2.

In that case then you are casting a negative number to float, and the first bit is probably being interpreted incorrectly for your expectations.

The following tests confirm my assumption:

// Force diffus to be a negative number.
uint64_t diffus = 20 - 30;
float diff = static_cast<float>(diffus);
float diffMS = diff / 1000;
std::cout << diffMS << " ms" << std::endl;

// Result of casting negative integer to float.
1.84467e+16 ms

// Force diffus to be a positive number.
uint64_t diffus = 30 - 20;
float diff = static_cast<float>(diffus);
float diffMS = diff / 1000;
std::cout << diffMS << " ms" << std::endl;

// Result of casting positive integer to float.
0.01 ms

Upvotes: 1

A float is normally a 32 bits number, so consider the consequences of doing this for further applications...

uint64_t diffus = ms.getT1 - ms.getT2
float diff = static_cast<float>(diffus);

on the other hand, float numbers can be represented in several ways.... (scientific notation for example) and that is only about how the number will look like, not about the number is holding..

3.1
3.14
3.14159

could be the same pi number printed in diff formats according to the needs of the application...

If your problem is about the representation of a float number then consider to set the precision of the cout object: std::cout.precision, here more info

std::cout.precision(2);
std::cout << diffMS << " ms" << std::endl;

Upvotes: 0

Related Questions