Profiling on macos with Instruments

Detail Panel

  • Weight: Describes the overall time taken executed by parent method if it contains nested methods. Let us say method A calls methods B and C. Then weight gives the time taken to execute method A which includes the time for B and C too.
  • Self weight: Describes the weight of a single method. By drilling down to method A in our previous case, you can observe the weight taken by methods B and C, which will be reflected in Self weight.
  • Symbol name: Represents thread name in which methods are running. And when drilled down, you can see the method names and also the system libraries if you have opted to see.
  • Call Tree: A filter which helps you in detecting actual time constraints from methods.

Let us see, how we can alter the logic by using Time Profiler in actual application. Here we will compare with a simple for loop and while loop case to identify which one actually executes faster. We are not considering the resource usage in this example.

Example shell script to profile program

#!/bin/sh
# CPU profiler for MacOS
# Running:
# cpu_profile /usr/bin/grep \
#              -- prog opts

set -o errexit
set -o nounset

if [ "$#" -lt 1 ]
then
  echo "Usage $0 <program> [arguments...]" 1>&2
  exit 1
fi

PROGRAM="$(realpath "$1")"
shift

OUTPUT="/tmp/cpu_profile_$(whoami)_$(basename "$PROGRAM").trace"
echo "Profiling $PROGRAM into $OUTPUT" 1>&2
# Delete potential previous traces
rm -rf "$OUTPUT"
xcrun xctrace record \
  --template 'CPU Profiler' \ ## Change this if you have a different template
                              ## you want to use
  --no-prompt \
  --output "$OUTPUT" \
  --target-stdout - \
  --launch -- "$PROGRAM" "$@"
open "$OUTPUT"

References:


No notes link to this note