Both the cities are well connected via train taking about 2.5 hrs minimum and via road 6 hrs min . I would suggest 4 days in Barcelona and 3 days for Madrid to be able to spend just the right amount of time to cover all important landmarks and get the feel of this places .