user5716859
user5716859

Reputation: 63

Slowdown issue if C function is placed in a separate file?

I am experiencing some strange slowdown issues with my program, written in C.

I have the following code:

typedef struct {
   Uint8 r;
   Uint8 g;
   Uint8 b;
   Uint8 alpha;
} COLOUR;

COLOUR get_colour(int r, int g, int b, int alpha) {
   COLOUR colour;

   colour.r = r;
   colour.g = g;
   colour.b = b;
   colour.alpha = alpha;

   return colour;
}

I then insert something like this in my main loop, just to reproduce my issue:

for (i = 0; i < 640 * 480; i++) {
   blue = get_colour(0, 0, 255, 255);
   yellow = get_colour(255, 255, 0, 255);
}

This works fine, no slowdowns yet.

BUT, if I move the code for my function get_colour() to a separate .C file (I prefer to store such functions in a library), I start getting slowdowns. Just the simple for-loop above causes my frame rate to drop from 100+ fps down to 70 fps.

Moving the code for my function get_colour() back to the same .C file as the rest of the code restores the speed back to normal.

What is causing this?

My compiler is GCC under MinGW, if that has anything to do with it.

Thank you very much for any answers.

Upvotes: 4

Views: 69

Answers (1)

Ziffusion
Ziffusion

Reputation: 8933

This is almost certainly because of inlining vs not. There is a comment above that mentioned that using the inline keyword in the other file doesn't work.

What you need to do is define the inline functions in a .h file, and include it above main(). Don't forget to use the -O flag during compile to enable inilining.

In bar.h:

typedef struct {
   Uint8 r;
   Uint8 g;
   Uint8 b;
   Uint8 alpha;
} COLOUR;

inline COLOUR get_colour(int r, int g, int b, int alpha) {
   COLOUR colour;

   colour.r = r;
   colour.g = g;
   colour.b = b;
   colour.alpha = alpha;

   return colour;
}

In foo.c:

#include "bar.h"

int main() {
    int i;
    COLOUR blue, yellow;
    for (i = 0; i < 640 * 480; i++) {
       blue = get_colour(0, 0, 255, 255);
       yellow = get_colour(255, 255, 0, 255);
    }    
}

Upvotes: 3

Related Questions