Are you sure you want to use a CGI script for this? Users are rarely patient enough to wait ten minutes for a script to finish.
You don't say what you're using this script for, but consider submitting the request to a queue and notifying the user that they will receive an email with the results in approximately ten minutes. Or, if it's not personalized (or if you know ahead of time who your audience is), have the script run on a cron job and write the results to a static html page.
You know what your needs are; consider if you're doing it the right way.