First, you compile the program using "-pg" option:
$ gcc -pg -o a.out test.cc
or
$ g++ -pg -o a.out test.cpp
Then run the program:
$ a.out
This will generate a file "gmon.out". We will use gprof to view it:
$ gprof a.out gmon.out
Read the man page of gprof to understand the output.