Profiling With Gprof

As promised, today I’ll be talking about GProf.

What Is GProf?

Gprof is a profiling tool. There are two versions: the original written for BSD UNIX, and a re-implementation for Linux. There are some minor differences between the two that you can read about here. We are going to concern ourselves with the Linux version.

Gprof is a pretty bare-bones utility. In the spirit of UNIX it does just one thing well. It doesn’t have any fancy menus or exotic extras. You just run it and it goes.

Preparing Your Program

First things first, we need to compile and link our program with profiling enabled. Using gcc, this is easy; just add -pg to the compile and linking options. If you’re using NetBeans, this is simple as well.

In NetBeans, right click your project and click Properties

Click Build > C Compiler. In the Additional Options field, add -pg to the end.

Click Build > Linker. In the Additional Options field, add -pg to the end.

Click OK. You are now good to go. Clean and build your project and you are ready for the next step.

Run Some Test Cases

Here is where things get confusing. You’ve compiled your program, surely you have to run your application within gprof similar to how you ran Valgrind, right? Let’s give that a shot…

# gprof [your_program] gmon.out: No such file or directory

Hmm… I’ll save you some time: Google will tell you that gmon.out should be there, clearly you messed something up and you’re a bad person.

Here’s the secret: you aren’t supposed to run your program through gprof at first. You need to run your program by itself first and it will create gmon.out in the current directory upon termination. Repeated runs will replace the existing gmon.out file. Run your application and perform some test cases. Follow good test practices and really stress your program. Now, you are ready to generate your profile data. Make sure gmon.out is in the current working directory and then…

gprof [your_program] > [output_file]

GProf should return without error and there should be a new file. Open it up in your favorite text editor. As you can see, it contains a flat profile, and a call graph of your program. Below each is a description of the columns. You should be able to take it from here, but if you want additional information check out the GNU gprof webpage.

Oh yeah, and don’t forget to remove the -pg from your compiler and linker lines when you’re done; they’ll tank your performance.

One response to “Profiling With Gprof”

  1. rody says :

    Very usefull thank you


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: