Search code examples
pythonmatplotlibplotfiguretimeit

Plot algorithm excution time in Python


I am trying to compare the execution time of two algorithms. till now, I've appended the start and end execution time in a list as follows:-

myList = [['algorithm_1', start time, end time], ['algorithm_2', start time, end time]]

Example

myList = [['algorithm_1', 1647030884.8106081, 1647030884.811373], ['algorithm_2', 647030884.8262258, 1647030890.0927901]]

The time measured in seconds

My question: could you please advise how to plot the difference between the start time and end time (algorithm execution time) of both algorithms in the same figure?

here is my code:

def get_algorithm_execution_time(algorithm_name):
    time_list = timeit.repeat(stmt=algorithm_name,
                              setup='',
                              timer=time.perf_counter,
                              number=1, globals=globals())
    execution_time = min(time_list)
    return execution_time

start_time = time.time()
execution_time = get_algorithm_execution_time('algorithm_1')
end_time = start_time + execution_time
algorithms_execution_time.append(['algorithm_1', start_time, end_time])

start_time = time.time()
best_time = get_algorithm_execution_time('algorithm_2')
end_time = start_time + execution_time
algorithms_execution_time.append(['algorithm_2', start_time, end_time])

start = []
end = []
plt.figure(figsize=(14, 6))
fig, ax = plt.subplots()
for i in algorithms_execution_time:
    start.append(i[1])
    end.append(i[2])
plt.plot(start[0], end[0], "b")
plt.plot(start[1], end[1], "r")
plt.show()

Currently, the figure doesn't show anything.

Thank you.


Solution

  • You may use the next code snippet:

    def graph_series(list_of_execution_time):
        from matplotlib import pyplot
    
    
        values = {}
        for element in list_of_execution_time:
            if element[0] not in values:
                values[element[0]] = [(element[2] - element[1])]
            else:
                values[element[0]].append(element[2] - element[1])
        for key, value in values.items():
            pyplot.plot(value, markersize=20,label=key)
        pyplot.legend()
        pyplot.show()
    

    It takes a list of lists, iterates, creates a list of values for each algorithm, and plots it by matplotlib here is manual.

    Use pip to install it:

    pip install matplotlib
    

    You can check it by next code:

    You have to send more than 2 points to each algorithm to see the graph.

    myList = [['algorithm_1', 1, 2], ['algorithm_1', 1, 5], 
                ['algorithm_2', 1, 3], ['algorithm_2', 1, 6], ]
    
    graph_series(myList)
    

    Here is the result:

    Graph