The Porter's speech serves several different purposes. One is that is provides comic relief, it makes the audience laugh and keep laughing. But there has been a sustained knocking at the gate for a long time. It began in Scene 2 and is continuing into Scene 3. It is essential to show who is doing the knocking and why. The Porter has to be drunk to explain why it took him so long to come to the gate, and Shakespeare must have decided that he would make this explanation comical.
We finally see who has been doing all this knocking. It is Macduff. He has been sleeping outside the castle all night, but he has been ordered to wake Duncan in the morning. The knocking was solely intended to force Macbeth to come out of his bedchamber in his nightgown so that he would be present when Macduff discovers the King's murdered body. This is the only time Macduff and Macbeth appear together before their death duel in the last act of the play. Shakespeare had to show them together at least one time before they meet on the battlefield at the end.
The audience might wonder about a lot of things, such as why Duncan didn't order someone who would be sleeping inside the castle to wake him, and why Macbeth would allow the entire household staff to get drunk when they are hosting the king and his two sons. The comedy and laughter distract the audience and keep them from thinking about such plot questions. No doubt Shakespeare had a man in his company who was good at making audiences laugh, and he made use of him here.
Following on the grisly murder of King Duncan at the end of Scene ii, Act II, Scene iii opens with the comical protestations of the drunken porter of Inverness. Some critics have famously seen in this episode Shakespeare's concession to his audience benumbed by the sheer horror of the regicide. That may be so, but the mature tragedian is accomplishing a lot more than providing slapstick comic relief. The porter's speech while leading to laughter nevertheless contributes to the larger meaning of the play and is itself a subtle commentary on it. His besotted banter parodies Macbeth's inner torment. This in turn creates a paradox since it is his banter which extends the time between Duncan's murder and the discovery of the body, thereby increasing the tension.
In the porter's reference to himself as Beelzebub's gatekeeper, Act Two's spinechilling metaphor is born in ironic laughter. Macbeth's castle is the vestibule of hell. For the duration of the play the audience will see in Macbeth's power drunk ambition and his wife's fiendish bloodthirstiness the machinations of the Devil.
The porter episode, global in its humour, therefore performs two functions: It lightens the suspense, if even for a moment, but it also expands Shakespeare's dramatic modus operandi, giving the audience an insight into the metaphorical structure of the play.