Using std :: chrono :: duration :: rep with printf in 32-bit and 64-bit programs

There is this code:

#include <cstdio>
#include <chrono>

int main()
{
  auto d = std::chrono::microseconds(1).count();
  printf("%lld", d);
  return 0;
}

When this is compiled in 64-bit mode, a warning appears:

main.cpp: In function ‘int main()’:
main.cpp:7:19: warning: format ‘%lld’ expects argument of type ‘long long int’, but argument 2 has type ‘long int’ [-Wformat=]
   printf("%lld", d);
                   ^

This warning is missing when compiling in 32-bit mode (with the -m32 flag). It seems to be of std::chrono::duration::reptype long intin 64-bit programs and long long intin 32-bit programs.

Is there a portable way to print it as a specifier %zufor size_t?

+7
source share
7 answers

Instead of using a qualifier, autouse a fixed integer int64_t size.

#include <cstdio>
#include <chrono>
#include <cinttypes>

int main()
{
    int64_t d = std::chrono::microseconds(1).count();
    printf("%" PRId64 "\n", d);
    return 0;
}
+3
source

, std::cout , 1 long long int 2 :

printf("%lld", static_cast<long long int>(d));

, auto specifier:

long long int d = std::chrono::microseconds(1).count();
printf("%lld", d);

1 , .
2 long long int 64 , . SO.

+8

std::cout, ++. .


, printf, :

printf("%lld", d);

:

#include <cinttypes>
printf("%" PRId64 "", d); 

d ( ), :

printf("%lld", static_cast<long long int>(d));
+4

long long int:

#include <cstdio>
#include <chrono>

int main()
{
  auto d = std::chrono::microseconds(1).count();
  printf("%lld", static_cast<long long int>(d));
  return 0;
}

, std::cout

+4

( ++), std:: cout

 {
   // create a string:
   std::ostringstream ss; 
   ss << d;" 
   // then
   printf("%s", ss.str().c_str());
 } 

, ,

 {
   printf("%s", std::to_string(d).c_str() );
 }
+2

, d long long int.

printf("%lld", static_cast<long long int> (d));
0

Perhaps this is not directly related to the 32/64 bit problem, but some of us work on embedded systems with odd output consoles and C ++ libraries. (In addition, we know that if we need to do some serious formatting of the output, printf is more intelligent than iomanip!)

In any case, it prints guts of duration and may be useful for debugging:

template<typename Rep, typename Ratio>
printf_dur( std::chrono::duration< Rep, Ratio > dur )
{
    printf( "%lld ticks of %lld/%lld == %.3fs",
            (long long int) dur.count(),
            (long long int) Ratio::num,
            (long long int) Ratio::den,
            ( (Ratio::num == 1LL)
              ? (float) dur.count() / (float) Ratio::den
              : (float) dur.count() * (float) Ratio::num
            )
         );
}
0
source

Source: https://habr.com/ru/post/1684816/


All Articles