简体   繁体   中英

Will std::cout affect timers?

I have a graphics program, and I want to measure the time certain function calls take. Since I am not sure how std::cout works under the hood, I wanted to ask if calls to it in between timer calls could affect performance. I know that it's slow in itself so I will naturally not put it in the functions I'm measuring, but is it buffered/asynchronous so that the effect will linger after the call returns in any way? I am looking to do something like this (pseudocode):

timer->Start();
RunSomeFunction();
timer->Stop();
std::cout << timer << std::endl; // Could this affect the next timer event?
timer->Start();
RunAnotherFunction();
timer->Stop();
std::cout << timer << std::endl;
// etc

In short, no.

Longer answer: However, it does depend, where cout is going to, and what system you are actually running on.

Typically, the internals of cout will use some sort of "write to file" system call, where file is the "standard out" filehandle - which may be some sort of display device, a window or a file if the output is redirected. This MAY of course lead to some sort of interrupt or some process elsewhere running (eg the "cmd.exe" in Windows or "xterm" or similar in Linux/Unix). If the functions are VERY short, this sort of "interference" may be sufficient to alter the results - of course, it's equally possible that your web-browser waking up to check if facebook has any new items, or your email software, or even just a network from some other system has a similar effect. However, in a modern system with a decent multi-core processor (as long as the system isn't already running 100% cpu usage), these effects should be fairly small and not really account for much - whether we are talking cout or any of the other potential factors.

Edit: Additionally, for very sensitive code, the effect of calling cout (or any other function that is more than a couple of lines long [or loops around reading large lumps of memory, even if few lines]) will affect the cache-content, which may affect the execution of the code.

Technically, std::cout (as well as most functions) can cause some RAM pages to be swapped out, or fill OS's buffers, or create an additional load for an OS in some other way. But that shouldn't be noticeable.

Any additional (asynchronous) work, either inside your process or in OS kernel, will be performed in another thread, so your program will not suffer from that much (provided that you have a multi-core CPU and your system is idle).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM