user20150: I have made a chess engine, and it seems from cProfile that my most expensive function is the one that calculates attack squares for both players. Here is the cProfile results for a perft function I wrote that goes 4 ply deep: https://imgur.com/a/VMoF3G5
The reason why my calculate attack squares function is so expensive is because every time a move is made in perft, the position is a new one, and attack squares for both players have to be recalculated. My question is this: Is there a more efficient way to be calculating attack squares for both players? Is there a way I can avoid having to recalculate attack squares for all 32 pieces every time a move is made in perft? Thank you.
https://repl.it/@kasparov/ImportantNotedCoderesource
My code for anyone who's curious

user13585: It may help to keep a list of each piece and the squares it attacks for the position. 
Then when a move occurs, you can reduce the work calculating for the pieces that don't move. Non-moving kings, knights, and pawns will attack the same squares as before. Non-moving queens, bishops, and rooks only need to be recalculated if a piece moved to or away from a square they attacked.
Then you can update the attack squares of the pieces that actually moved.

20150: <p>I have made a chess engine, and it seems from cProfile that my most expensive function is the one that calculates attack squares for both players. Here is the cProfile results for a perft function I wrote that goes 4 ply deep: <a href="https://imgur.com/a/VMoF3G5" rel="nofollow noreferrer">https://imgur.com/a/VMoF3G5</a></p>

<p>The reason why my calculate attack squares function is so expensive is because every time a move is made in perft, the position is a new one, and attack squares for both players have to be recalculated. My question is this: Is there a more efficient way to be calculating attack squares for both players? Is there a way I can avoid having to recalculate attack squares for all 32 pieces every time a move is made in perft? Thank you.</p>

<p><a href="https://repl.it/@kasparov/ImportantNotedCoderesource" rel="nofollow noreferrer">https://repl.it/@kasparov/ImportantNotedCoderesource</a>
My code for anyone who's curious</p>
 13585: <p>It may help to keep a list of each piece and the squares it attacks for the position. </p>

<p>Then when a move occurs, you can reduce the work calculating for the pieces that don't move. Non-moving kings, knights, and pawns will attack the same squares as before. Non-moving queens, bishops, and rooks only need to be recalculated if a piece moved to or away from a square they attacked.</p>

<p>Then you can update the attack squares of the pieces that actually moved.</p>
