Which One is faster

My question is as follows..

What is a faster a loop that prints a statement to the screen 1000 times or 1000 print statements that each displays something..
I'm confused..

In my opinions 1000 print statements should be fast than a 1000 iterations of a loop.. because in a loop every time condition is checked increment process is done..
Last edited on
I beg to differ. The compiler usually will optimize the loop so that the overhead of checking the conditional variable is almost nil.

With 1000 print statements, you have to push arguments onto the stack, invoke the function,
return from the function and adjust the stack.

The fastest way to tell is to run your own tests.
Here's a small program that demonstrates loop-unrolling with template meta-programming. The performance gain should become bigger as the loop count becomes greater.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

template<int num>
void display_loop(const std::string& s)
{
    std::cout<< num<< ": "<< s<< std::endl;
    display_loop<(num - 1)>(s);
}

template<>
void display_loop<0>(const std::string& s __attribute__((unused)))
{
}

inline void traditional_display_loop(const std::string& s, const unsigned long long int& count)
{
    for(unsigned long long int x{0}; x < count; ++x) std::cout<< (count - x)<< ": "<< s<< std::endl;
}

int main()
{
    display_loop<500>("Hello World!");
    //traditional_display_loop("Hello World!", 500);
}


Again, the only real difference is that there is no variable, variable tests, or jump. The performance gain is almost neglegible.
Last edited on
The overhead of an increment, if and jump is going to be negligible compared to a single printf statement which has to interpret the format, build the output buffer, then flush the buffer to the screen. printf is very expensive.

koothkeeper wrote:
With 1000 print statements, you have to push arguments onto the stack, invoke the function, return from the function and adjust the stack.

Those arguments still have to be pushed onto the stack during each iteration of the loop.
@AbstractionAnon: Agreed; however, some compilers can even optimize that overhead.
Some compilers are that smart, that can do something like that forever:
1
2
3
4
[[ noreturn ]] void print(unsigned a){
    printf("%d", a);
    print(a + 1);
}

My mcvs doesn't use call stack for this, it works like normal loop.
Topic archived. No new replies allowed.