Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program run way faster when I enable profiling?

Tags:

c++

I have a program that's running pretty slowly (takes like 20 seconds even on release) so, wanting to fix it, I tried to use Visual Studio's built in profiler. However, when I run the program with profiling enabled, it finishes in less than a second. This makes it very difficult to find a bottleneck. I would post the code but it is long. Are there any obvious or not so obvious reasons why this would be happening?

EDIT: Ok so I narrowed the problem down to a bunch of free() calls. When I comment them out, the program runs in the same amount of time that it does with profiling enabled. But now I have a memory leak :-/

like image 763
Stewart Avatar asked Dec 26 '09 22:12

Stewart


4 Answers

The reason is because when you run your application within Visual Studio, the debugger is attached to it. When you run it using the profiler, the debugger is not attached.

If you press F5 to run your program, even with the Release build, the debugger is still attached.

If you try running the .exe by itself, or running the program through the IDE with "Debug > Start Without Debugging" (or just press Ctrl+F5) the application should run as fast as it does with the profiler.

like image 200
Shane Avatar answered Nov 14 '22 15:11

Shane


That sounds a lot like a Heisenbug.

They really happen, and they can be painful to uncover.

Your best solution in my experience is to change how you are profiling -- possibly several ways -- until the bug disappears.

Use different profilers. Try adding timing code instead of using a profiler.

like image 25
Drew Dormann Avatar answered Nov 14 '22 14:11

Drew Dormann


turning on the profiler will end up moving your code around (a bit) which probably masking the problem.

The most common cause of hiesenbugs is unitialized variables, The second most common cause is using memory after it has been freed(). Since your free seems to fix it, you might think to look for late references, but I would still look for uninitialized variables first if I were you.

like image 5
John Knoeller Avatar answered Nov 14 '22 13:11

John Knoeller


In my case it was due to the Windows Timer Resolution.

If you program uses threading, the System wide Timer resolution may be the reason for longer times when running through Visual studio.

The default windows timer resolution is 15.6ms

When running through profiler, the profiler sets this value to 1ms causing faster execution. Checkout this answer

like image 1
Kusal Dissanayake Avatar answered Nov 14 '22 13:11

Kusal Dissanayake