0

I am measuring the amount of time printf and cout are for a given output (a number), and want to know if there is a better way of measuring nanosecond precision in C++ (or if this code needs improving).

int rand1 = rand();
auto start = std::chrono::high_resolution_clock::now();
printf("%d", rand1);
auto finish = std::chrono::high_resolution_clock::now();
double secondsPrintf = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count();
auto start1 = std::chrono::high_resolution_clock::now();
std::cout << rand1;
auto finish1 = std::chrono::high_resolution_clock::now();
std::cout << endl; // measuring performance of printing the number, no need for endl (drastically lowers performance)
double secondsCout = (double)std::chrono::duration_cast<std::chrono::nanoseconds>(finish1-start1).count();

I heard chrono's now() function is very precise, but is there a better way (or more efficient, quicker, etc.) to do any of these operations?

Bob
  • 41
  • 1
  • 8
  • `std::cout` should be *theoretically* faster than `printf(const char*, ...)`, because it doesn't have to evaluate the variable arguments. Rest is implementation defined – iammilind May 19 '13 at 03:58
  • Thanks for your comment @iammilind. Is there a source on that I can read more about? – Bob May 19 '13 at 04:00
  • Is the question really just about timing? It doesn't seem to really have anything to do with cout/printf at all. – Matt Phillips May 19 '13 at 04:10
  • It's about how many nanoseconds it takes to print out a random integer. – Bob May 19 '13 at 04:12
  • If you find a more fine-grained way to measure performance on your system, report it to the implementers of your standard library. – Benjamin Lindley May 19 '13 at 05:07
  • 2
    Printing N numbers in a loop and dividing the time by N will give you better results. – Begelfor May 19 '13 at 07:23
  • I doubt that you will be able to get real *nanosecond* precision timings this way. While the precision of the function might be nanoseconds, I doubt that the accuracy is close to that. – David Rodríguez - dribeas May 19 '13 at 14:12

0 Answers0