How to split links generated into an xml sitemap to avoid exceeding 30 sec maximum execution time?

So I am trying to push these kind of URLs into a sitemap www.example.com/used-cars/location/new-york/model/audi & www.example.com/used-cars/model/bmw

This code seems to do exactly that:

`
add_filter( ‘wpseo_sitemap_index’, ‘add_sitemap_custom_items’ );
function add_sitemap_custom_items(){

$models = get_terms( array(
    'taxonomy' => 'vehicle_model',
    'hide_empty' => true,
) );
$locations = get_terms( array(
    'taxonomy' => 'vehicle_location',
    'hide_empty' => true,
) );

// Loop through the search terms
$pages = '';

foreach ( $models as $model ) {
    $location2 = home_url( '/used-cars/model/' . $model->slug );
    $pages .= "<sitemap><loc>$location2</loc><lastmod>2017-04-04T23:59:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></sitemap>\n";
    foreach ( $locations as $location ) {
        $location2 = home_url( '/used-cars/location/' . $location->slug . '/model/' . $model->slug );
        $pages .= "<sitemap><loc>$location2</loc><lastmod>2017-04-04T23:59:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.8</priority></sitemap>\n";
    }

}
return $pages;
}

`

But now the problem is that, I get a fatal error of Maximum execution time of 30 seconds exceeded in C:\wamp\www\autocity\wp-includes\class-wp-hook.php on line 284
Call Stack
, So my guess is that I need to split these links into multiple sitemap files, with each file not having more than 30k links. How do I do that?

Oh and the code generates 84k links. I would like to split these into atleast 20k per sitemap file.

Solutions Collecting From Web of "How to split links generated into an xml sitemap to avoid exceeding 30 sec maximum execution time?"