C MACRO to trace the "for" loop iteration in the existing source code

166 Views Asked by At

I require a c/c++ MACRO to trace the "for" loop iterations in the existing source code and to print some message if loop is running more that 50 iterations. NOTE: the macro should not change the existing functionality of code. I tried some logic C/C++: "for" macro to track loops which are running many iterations but it is not working in all cases!

  int main()
  {
    int i,j,x,y;
    j=100;
    y=200;

    //case 1
    for(i=0;i<j;i++)   
        for(x=0;x<y;x) 
        x++;


    //case 2
    if(i>0)
      for(;i>0;)    
        i--;

     //case 3
     for(;;)  
     {
        i++;
     }

     return 0;
}
1

There are 1 best solutions below

2
On

Here is a proof of concept that passes all three cases:

// Max lines in a file you are profiling
#define MAX_LINES 65535
// Array to count all iterations, initialized to zero
uint32_t iterations[MAX_LINES];
// Increments the iteration for the given line, returns non-zero
#define ITER(ln)  ++iterations[ln]
// Override for definition
#define for(...) for(__VA_ARGS__) if (!ITER(__LINE__)) { } else

The limitation here is that you can only have one for per line, otherwise it will combine their iterations. So, this is okay:

for(i=0;i<j;i++)   
    for(x=0;x<y;x)
        x++;

but this isn't:

for(i=0;i<j;i++) for(x=0;x<y;x) x++;

The other limitation is that we define an array for every line. You can easily make it a hashmap or something, but that isn't relevant for this example. With a hashmap, you can use the __LINE__ and #x (string representation of the loop) to construct the ID, so the first limitation mostly goes away as well.