Booked this excursion a few years ago it included a very nice lunch and was quite expensive. However we were VERY rushed and could not enjoy the lunch as time ran out. The train was very crowded and uncomfotably hot. Do your own thing but you will hardly have time to get out of the railway station if you've only got four hour in port.
The timetable for the Flam railway can be found under the Flaamsbana website. The round trip from Flaam to Myrdal and back on the same train takes one hour and forty minutes so is quite feasible. What I would suggest is that you get off the ship as soon as it docks and walk the hundred yards from the berth to the railway station, check the timetable and book the first train out. That way you will know that you will be able to get back on time for the ship's departure. One other tip - sit on the right side of the carraige on the way up - you get the best of the valley from there and yes the trip is fantastic!
The train from Flåm to Myrdal takes 55 min. and costs NOK 190,- (about £19).
For timetables and more information see www.nsb.no (there is information in English). Be sure and sit on right side of train.When the train stops and you get off at waterfall walk all the way back or left.A girl dances in falls and if you stay to far right you will miss her.
Bear in mind that you only have 4hrs in port, you will have to be back on board well before sailing, and you will probably not be the only ship in port, so you may have to queue to get tickets. Personally I think it all sounds a bit rushed but it is up to you.