Help optimizing performance of a fairly simple Python function

CUclimber

Ars Legatus Legionis
19,626
Subscriptor
I have a function that is used repeatedly in a script, and I'm finding that it's taking approximately forever to run. I am wondering if there's something obvious that I can do to make it more efficient.

It takes 2 inputs:
First is fairly large list of dictionaries (up to around 1,000,000 items), with each dictionary containing two keys, like:
{'id': id_string, 'amount': amount_int}

The second input is a smaller list (50,000 to 100,000) of just strings of ids:
[id1, id2, id3... idn]

I want to find the sum of the 'amount' values in the big list of dictionaries if the 'id' key is present in the list of ids.

What I have now is:
Code:
def my_func(big_list, list_of_ids):
    total = sum([d['amt'] for d in big_list if d['id'] in list_of_ids])
    return total

So pretty straightforward. The problem is that it's taking what seems to be a very long time to do that calculation-- upwards of 10 minutes when the list of dictionaries is 750k records and the smaller list of ids is 75k records. When I have to do this 50+ times it means that the program takes many hours to complete.

Am I missing an obvious way to do this quickly? Or do I just need to accept that this is a very inefficient kind of calculation? There are some other areas in the code where I'm doing set intersections and those are super fast-- is there some way to essentially do that with the two lists and filter the dictionaries out that way?

Thanks in advance.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
I have a function that is used repeatedly in a script, and I'm finding that it's taking approximately forever to run. I am wondering if there's something obvious that I can do to make it more efficient.

It takes 2 inputs:
First is fairly large list of dictionaries (up to around 1,000,000 items), with each dictionary containing two keys, like:
{'id': id_string, 'amount': amount_int}

The second input is a smaller list (50,000 to 100,000) of just strings of ids:
[id1, id2, id3... idn]

I want to find the sum of the 'amount' values in the big list of dictionaries if the 'id' key is present in the list of ids.

What I have now is:
Code:
def my_func(big_list, list_of_ids):
    total = sum([d['amt'] for d in big_list if d['id'] in list_of_ids])
    return total

So pretty straightforward. The problem is that it's taking what seems to be a very long time to do that calculation-- upwards of 10 minutes when the list of dictionaries is 750k records and the smaller list of ids is 75k records. When I have to do this 50+ times it means that the program takes many hours to complete.

Am I missing an obvious way to do this quickly? Or do I just need to accept that this is a very inefficient kind of calculation? There are some other areas in the code where I'm doing set intersections and those are super fast-- is there some way to essentially do that with the two lists and filter the dictionaries out that way?

Thanks in advance.

That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.
 

Fruity Pebbles

Ars Praetorian
595
Subscriptor
I was too curious to not try it. Using randomly generated data with 'big_list' size 1,000,000 and 'list_of_ids' size 100,000, I get run times of 48 seconds with the IDs in a list, and 0.13 seconds with the IDs in a set.

Code:
import time
import numpy as np


def generate_data(big_size: int, active_size: int):
    assert big_size >= active_size, "Too many active IDs"

    # generate big_list
    big_ids = np.arange(big_size)
    big_amounts = np.random.randint(1, 100, big_size)
    np.random.shuffle(big_ids)
    big_list = list()
    for index in range(big_size):
        big_list.append({'id': big_ids[index], 'amt': big_amounts[index]})

    # generate active IDs list
    np.random.shuffle(big_ids)
    active_ids = big_ids[:active_size]

    return big_list, active_ids


def my_func(big_list, list_of_ids):
    total = sum([d['amt'] for d in big_list if d['id'] in list_of_ids])
    return total


def main():
    big_list, id_list = generate_data(1000000, 100000)

    # Time how long it takes to perform my_func with a *list* of IDs
    start = time.perf_counter()
    t1 = my_func(big_list, id_list)
    elapsed1 = time.perf_counter() - start

    # Convert the list of IDs to a set
    id_set = set(id_list)

    # Time how long it takes to perform my_func with a *set* of IDs
    start = time.perf_counter()
    t2 = my_func(big_list, id_set)
    elapsed2 = time.perf_counter() - start

    print("Total list: {}    Total set: {}".format(t1, t2))
    print("Time list: {}    Time set: {}".format(elapsed1, elapsed2))


if __name__ == "__main__":
    main()
 

CUclimber

Ars Legatus Legionis
19,626
Subscriptor
I'm not sure why I didn't consider keeping the ids as a set-- that is stupendously faster and it's a perfect solution.

Since I don't have a great background in the inner workings of how sets vs. lists work, could someone educate me a bit on why this is so much better? What is the technical difference between a set and a list that would give it such a huge performance increase?
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
I'm not sure why I didn't consider keeping the ids as a set-- that is stupendously faster and it's a perfect solution.

Since I don't have a great background in the inner workings of how sets vs. lists work, could someone educate me a bit on why this is so much better? What is the technical difference between a set and a list that would give it such a huge performance increase?
Usually, sets have an entirely different data structure behind them. A list is just a continuous bit of memory*, that means that to find something in it you have to check against each value. If it is sorted, then you can do better, but that takes a significant amount of time. On the other hand, sets are usually built on a tree or hash table of some sort and optimized for membership checks (you have to do one every time you add something). These are data structures which make finding something much quicker because you don't have to look at many things at all. Depending on the particular data structure, the performance becomes either as good as a sorted list, or basically instant (trading memory for speed).

* Sort of, there might be some variance on that to support changing the size, but they are designed to act sort of like they are a single block of memory.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.
 

Fruity Pebbles

Ars Praetorian
595
Subscriptor
I'm not sure why I didn't consider keeping the ids as a set-- that is stupendously faster and it's a perfect solution.

Since I don't have a great background in the inner workings of how sets vs. lists work, could someone educate me a bit on why this is so much better? What is the technical difference between a set and a list that would give it such a huge performance increase?

Think of a set as a reference book with an index. If you want to look up something you flip to the index and find your subject, then flip directly to the page you need.

A list is like a reference book with the index ripped out. When you want to look up something you start at page 1 and read until you find what you're looking for. Every time.
 

Fruity Pebbles

Ars Praetorian
595
Subscriptor
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.

Hmm, I think the opposite. Since you're iterating the longer list once you wouldn't gain any speed by switching from list to map. On the other hand, you'd save quite a bit of memory by dropping the strings for the inner dictionary keys.

Original representation of data: [{'id': 1, 'amount': 2}, {'id': 2, 'amount': 4}, {'id': 3, 'amount': 6}]

Data as a single map: {1: 2, 2: 4, 3: 6}
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.

Hmm, I think the opposite. Since you're iterating the longer list once you wouldn't gain any speed by switching from list to map. On the other hand, you'd save quite a bit of memory by dropping the strings for the inner dictionary keys.

Original representation of data: [{'id': 1, 'amount': 2}, {'id': 2, 'amount': 4}, {'id': 3, 'amount': 6}]

Data as a single map: {1: 2, 2: 4, 3: 6}

Yes, that would be the point in the change: you can iterate over the smaller one which is faster than iterating the bigger one. Turn the larger one in a map and the iterate the smaller one as keys to the map. It would be ten or so times faster.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.

Hmm, I think the opposite. Since you're iterating the longer list once you wouldn't gain any speed by switching from list to map. On the other hand, you'd save quite a bit of memory by dropping the strings for the inner dictionary keys.

Original representation of data: [{'id': 1, 'amount': 2}, {'id': 2, 'amount': 4}, {'id': 3, 'amount': 6}]

Data as a single map: {1: 2, 2: 4, 3: 6}

Yes, that would be the point in the change: you can iterate over the smaller one which is faster than iterating the bigger one. Turn the larger one in a map and the iterate the smaller one as keys to the map. It would be ten or so times faster.

I was thinking the same thing earlier and almost posted it but I don't know Python syntax enough to feel confident saying it. No point in iterating over 1,000,000 things where 900,000 are misses when you can iterate over 100,000 things that are all hits (assuming that all the IDs in the list will always match something in the dictionary and that the dictionary does hash lookups on the keys in the kvp).
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.

Hmm, I think the opposite. Since you're iterating the longer list once you wouldn't gain any speed by switching from list to map. On the other hand, you'd save quite a bit of memory by dropping the strings for the inner dictionary keys.

Original representation of data: [{'id': 1, 'amount': 2}, {'id': 2, 'amount': 4}, {'id': 3, 'amount': 6}]

Data as a single map: {1: 2, 2: 4, 3: 6}

Yes, that would be the point in the change: you can iterate over the smaller one which is faster than iterating the bigger one. Turn the larger one in a map and the iterate the smaller one as keys to the map. It would be ten or so times faster.

I was thinking the same thing earlier and almost posted it but I don't know Python syntax enough to feel confident saying it. No point in iterating over 1,000,000 things where 900,000 are misses when you can iterate over 100,000 things that are all hits (assuming that all the IDs in the list will always match something in the dictionary and that the dictionary does hash lookups on the keys in the kvp).

That only works if you use a map for the bigger one. Otherwise you just iterate over both.
 

Fruity Pebbles

Ars Praetorian
595
Subscriptor
That's an n^2 algorithm. To make it faster, you need a different data structure. Turn the ids into a set or the big list into a map and it should help.

I'd try turning the ids into a set. That should give you a pretty dramatic improvement.

I actually would be tempted to drop the longer list into a map. That would make things even faster, but it would take more memory.

Hmm, I think the opposite. Since you're iterating the longer list once you wouldn't gain any speed by switching from list to map. On the other hand, you'd save quite a bit of memory by dropping the strings for the inner dictionary keys.

Original representation of data: [{'id': 1, 'amount': 2}, {'id': 2, 'amount': 4}, {'id': 3, 'amount': 6}]

Data as a single map: {1: 2, 2: 4, 3: 6}

Yes, that would be the point in the change: you can iterate over the smaller one which is faster than iterating the bigger one. Turn the larger one in a map and the iterate the smaller one as keys to the map. It would be ten or so times faster.

Right, I see what you're saying now. Yes, that would be both faster and use less memory.