4 ms·
> This looks innocent enough, but if your program prints a lot of stuff, this will become a huge bottleneck because each call to print! will first acquire a loc
by wyldfire 5y ago
> This looks innocent enough, but if your program prints a lot of stuff, this will become a huge bottleneck because each call to print! will first acquire a lock on stdout, then call format!, to resolve the formatting, and finally make a syscall to actually print
You've fallen for one of the two classic blunders! The first being never get involved in a land war in Asia but only slightly lesser known: never benchmark code that calls printf()/println!().
Ok, mostly joking. In this case, the author is actually trying to optimize the actual writing of the output itself so benchmarking the println!() is appropriate. But in many cases, you may write a naive benchmark that does something like <start a clock>; <do some work>; <print some output>; <do some work>; <stop the clock>;. Let's assume that unlike this article's author you don't actually want to optimize the printout it's just something your program happens to do. And maybe "do some work" takes hundreds of milliseconds or several seconds or something so who cares about a printout? Well, you do. Or you should. Because of all of the things that happen after your program initiates that system call. Your program's terminal could be connected over a slow or buggy RS232 line, or an ssh session over a noisy wifi link, or piped somewhere or redirected to a file on an unstable device. So your benchmark that's intended to measure the performance of the computation you're doing ends up being unreliable because of the flexibility of the write() call underneath that println!().