4

What is the actual result type of std::chrono::duration::count function like in the following case:

std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();

It seems like it is some rep type but what is it actually? I need to know the exact type to pass it to some other languages. Can I just cast it to long long, for example?

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

4

The type is std::chrono::milliseconds::rep. You can inspect this type with a function that prints out types. For example:

#include "type_name.h"
#include <chrono>
#include <iostream>

int
main()
{
    std::cout << type_name<std::chrono::milliseconds::rep>() << '\n';
}

For me (and probably for you too), this outputs:

long long
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • Ok, what should I do then? I need to pass this result type to another language so I need to know at least how large it is. – FrozenHeart Aug 02 '18 at 00:49
  • Just be careful of this, the *proper* type is the first one given, `std:chrono:milliseconds:rep`. Using `long long` may well be unportable if, for example, an implementation wants to provide enough bits to measure milliseconds from the big bang to the heat death :-) As to passing it to another language, if only there were some common representation. I think, if I were to invent this, I'd call it, I don't know, something like "text" :-) Note the smileys, I'm not intending to offend. – paxdiablo Aug 02 '18 at 00:49
  • `sizeof` is the C++ way to get the number of bytes a type or variable takes. And text is a good idea for passing among languages unless it is known a-priori that the two languages share the same binary representation for the type. – Howard Hinnant Aug 02 '18 at 00:56
2

From doc, count returns rep type which comes from template<class Rep, class Period = std::ratio<1>> class duration;

Moreover,

std::chrono::milliseconds   duration</*signed integer type of at least 45 bits*/, std::milli>

So it is implementation specific.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • This is why `auto` is such a good idea, sometimes you just shouldn't have to care :-) – paxdiablo Aug 02 '18 at 00:31
  • Ok, what should I do then? I need to pass this result type to another language so I need to know at least how large it is. – FrozenHeart Aug 02 '18 at 00:49
  • It depends. You might have code dependent of rep `type` to give appropriate type, or use your type and "convert" result to your type (as `std::int64_t`) (care with signed overflow :/). – Jarod42 Aug 02 '18 at 00:55
  • Frustrating C++ double talk! – d512 Mar 31 '22 at 02:43