We'll need to know which OS you're using before explaining how to defrag as they each have a slightly different way to run defrag.
The purpose is to ensure that your files and folders, which become 'scattered' (or fragmented) all over your HDD over time ,are brought together on the HDD. This is so the PC doesn't have to hunt all over the HDD to find a particular file or folder and, thus, it usually results in a slight increase in speed.
How long does it take? As long as piece of string. It depends entirely on the size of your HDD and the number of files and folders you have, The bigger the HDD and the more files and folders you have, the longer it will take to defrag.