Scene 3 of Act II is designed to provide comic relief after the succession of stressful scenes leading up to Duncan's murder. Shakespeare probably used an actor who specialized in comic roles to play the drunken Porter who admits Macduff after his prolonged knocking. The comedy is bawdy and scatalogical. It must have provoked loud laughter in Shakespeare's theater. Here is a typical example of the low comedy:
What three things does drink especially provoke?
Marry, sir, nose-painting, sleep, and urine.
Lechery, sir, it provokes and unprovokes: it provokes the
desire, but it takes away the performance. Therefore much
drink may be said to be an equivocator with lechery: it
makes him, and it mars him; it sets him on and it takes
him off; it persuades him and disheartens him; makes him
stand to and not stand to; in conclusion, equivocates him in
a sleep, and giving him the lie, leaves him.
But Shakespeare had a more important reason for inserting this scene than merely providing comic relief. The main purpose of the prolonged knocking at the gate and the Porter's slowness in responding is to force Macbeth to come down in his nightgown to find out what is going on. He planned to pretend to have been in bed asleep when Duncan was killed. In Act II, Scene 2, Lady Macbeth says:
Get on your nightgown, lest occasion call us
And show us to be watchers.
This indicates that Macbeth will be in his nightgown when he appears in Act II, Scene 3. But he can't pretend to be sleeping through all that knocking, which undoubtedly gets louder and more insistent until the Porter finally opens the gate.
Shakespeare wanted Macbeth to be present when Macduff discovers the king's body. This makes the discovery much more dramatic as well as easier to stage. The drunken Porter may be used for comic relief, but he is also used to explain why there had to be so much knocking. In Act II, Scene 1, Banquo tells Macbeth:
The king's abed.
He hath been in unusual pleasure and
Sent forth great largess to your offices.
This "largess" explains why Macbeth's entire household staff is drunk and doesn't respond to the knocking. Macbeth can hardly complain, since the king himself was responsible for getting all his servants drunk.
Thomas De Quincey wrote a famous essay "On the Knocking at the Gate in Macbeth" in which he focuses on the effect of the knocking. But he does not explain the purpose of the knocking, which is to force Macbeth to put in an appearance. When he does make an appearance he seems stiff and cold. This is because he is dreading the discovery of Duncan's body. But innocent Macduff thinks it is because Macbeth is angry at having been wakened out of a sound sleep. In reality Macbeth has never been to bed.