public function save_run($xhprof_data, $type, $run_id = null) {
        global $DB, $CFG;

        if (is_null($this->url)) {
            xhprof_error("Warning: You must use the prepare_run() method before saving it");
        }

        // Calculate runid if needed
        $this->runid = is_null($run_id) ? md5($this->url . '-' . uniqid()) : $run_id;

        // Calculate totals
        $this->totalexecutiontime = $xhprof_data['main()']['wt'];
        $this->totalcputime = $xhprof_data['main()']['cpu'];
        $this->totalcalls = array_reduce($xhprof_data, array($this, 'sum_calls'));
        $this->totalmemory = $xhprof_data['main()']['mu'];

        // Prepare data
        $rec = new stdClass();
        $rec->runid = $this->runid;
        $rec->url = $this->url;
        $rec->totalexecutiontime = $this->totalexecutiontime;
        $rec->totalcputime = $this->totalcputime;
        $rec->totalcalls = $this->totalcalls;
        $rec->totalmemory = $this->totalmemory;
        $rec->timecreated = $this->timecreated;

        // Send to database with compressed and endoded data.
        if (empty($CFG->disableprofilingtodatabase)) {
            $rec->data = base64_encode(gzcompress(serialize($xhprof_data), 9));
            $DB->insert_record('profiling', $rec);
        }

        // Send raw data to plugins.
        $rec->data = $xhprof_data;

        // Allow a plugin to take the trace data and process it.
        if ($pluginsfunction = get_plugins_with_function('store_profiling_data')) {
            foreach ($pluginsfunction as $plugintype => $plugins) {
                foreach ($plugins as $pluginfunction) {
                    $pluginfunction($rec);
                }
            }
        }

        if (PHPUNIT_TEST) {
            // Calculate export variables.
            $tempdir = 'profiling';
            make_temp_directory($tempdir);
            $runids = array($this->runid);
            $filename = $this->runid . '.mpr';
            $filepath = $CFG->tempdir . '/' . $tempdir . '/' . $filename;

            // Generate the mpr file and send it.
            if (profiling_export_runs($runids, $filepath)) {
                fprintf(STDERR, "Profiling data saved to: ".$filepath."\n");
            }
        }

        return $this->runid;
    }