Get startedGet started for free

Profvis: Larger example

1. Profvis

We've seen how profvis works with a relatively simple piece of R code. So let's turn the excitement up, and consider the board game of Monopoly.

2. Monopoly

The Monopoly game-board consists of forty spaces containing twenty-eight properties. The object of the game is to go round the board buying squares. If an player lands on the square owned by an opponent, they're charged money. A player can also be sent to jail for a variety of reasons, including throwing three consecutive doubles in a single turn. I've written some R code,

3. Monopoly Code

around one hundred lines long, that simulates Monopoly. It's indistinguishable from the real game except for two tiny points. First I've rejected the capitalist system and don't use money. Second I don't actually have any friends and so I play the game by myself. Other than these two minute differences, it's identical to the real thing. To simulate the game, we call the simulate_monopoly function and specify the number of turns we wish to take.

4. Monopoly profvis

Wrapping this function in profvis, will tells us the amount of time spent in each function. What's important, is that even though the code is over one hundred lines long, we have been able to easily pinpoint the bottleneck; the move_square function. If we can optimize this one function, we'll see a large overall improvement in performance. This particular function handles how we move around the board.

5. Monopoly profvis

The complexity of the function is because in Monopoly if we roll a double we get another turn. But if we roll three consecutive doubles, we go to Jail. The logic of the move_square function is in the first line of code, we perform all dice rolls at once and detect if there are any doubles. The if statements determine where we should move. profvis highlights a few key areas. The very first line of the simulate monopoly function is the major bottleneck. Around sixty percent of the time, we are just executing this line.

6. Monopoly profvis

The next major target is where we calculate row sums. In the next few exercises, you'll optimize this code. Before starting, take a second to think what you would change?

7. Let's practice!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.