6

Calculating time complexity in Python is very easy by comparing the time it takes to run an algorithm vs the size of the input. We can do something like:

import time

start = time.time()
<Run the algorithm on input_n (input of size n)>
end = time.time()
time_n = end - start

By graphing time_n vs input_n, we can observe whether the time complexity is constant, linear, exponential, etc.

Is there a similarly empirical, programmatic way of calculating the space complexity of an algorithm in Python, where we can measure the amount of space used as the input size grows?

FatihAkici
  • 4,679
  • 2
  • 31
  • 48
  • 1
    have you tried `memory_profiler `? – prhmma Nov 30 '19 at 09:48
  • @prhmma Thanks for the suggestion, no I haven't come across any method to accomplish my goal. Please give a sample usage as an answer so I can upvote/accept it. – FatihAkici Nov 30 '19 at 09:50
  • It's pretty straight forward on their repo, please check it [here](https://github.com/pythonprofilers/memory_profiler) – hunzter Nov 30 '19 at 09:53
  • For the record, this does not give the time complexity of the algorithm; it measures the actual running time for whichever input you used. There is no programmatic way to determine time complexity in general, since that would require solving the halting problem. – kaya3 Dec 03 '19 at 11:37

1 Answers1

10

you can use memory_profiler with a decorator like this:

from memory_profiler import profile

  @profile(precision=4)
  def func():
     your function

there another function called mprof in memory_profiler that will be useful too. This can be useful if you want to see if your memory is getting cleaned up and released periodically. just run mprof run script script_args in your shell of choice. mprof will automatically create a graph of your script's memory usage over time, which you can view by running mprof plot. it requires matplotlib though.

update: Thanks to @hunzter you can find documentation here.

prhmma
  • 843
  • 10
  • 18
  • https://stackoverflow.com/questions/74192299/mprun-magic-command-gets-error-could-not-find-file-tmp-ipykernel-75919-1494889 Don't run it in jupyter notebook – saravanan saminathan Aug 21 '23 at 10:36