How to record the 4k video in real time?

Just for info, cv::cudacodec::VideoWriter has been fixed and you should be able to use to write to raw .h264 and .hevc files if you have an Nvidia GPU. See here for an example.