How to measure performance of code ? – Basic methods

In this article, we will cover some very basic methods to calculate performance of script. In next article we will cover advance tool like cProfile and memory_profiler.

What is profiling?

  • Profiling is program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls.
  • Profiling or performance measurement is main tool for code optimization.
  • There are two types of profiling : Time profiling and Memory profiling
  • We should also consider memory leaks to optimize code.

1) Date

Run script by running date command before and after script to find time when script started execution and when it completed.

This prints time before running script and again print time when execution is complete. So we can find execution time by subtracting end time from start time.

2) time

Unix time command is helpful to figure out how much time command, shell script or python program takes for execution.
Usage:

output:

  • User : CPU time spent in user-mode (outside the kernel)
  • System : CPU time spent in the kernel
  • CPU : Percent of CPU this job got
  • Total : elapsed time, start to end

Why user + system ≠ total ?
total represents actual elapsed time, while user and sys values represent CPU execution time.

3) /usr/bin/time

/usr/bin/time gives more detailed output than ‘time‘.
Usage:

Output:

What is difference between usr/bin/time and time ?
time is built in unix command and usr/bin/time is GNU time

About Gaurav Vichare

Hi , I am Gaurav : author of this blog , Software engineer and a Photoshop lover . You can connect with me on Facebook , cirlce me on Google or follow on Twitter