# Section: Results
def write_results_and_exit(results):
    import dill
    import json
    import sys

    results['timings']['total'] = time.perf_counter() - time_start

    with open('{{ results.filename_output }}', 'w') as handle:
        json.dump(results, handle)

    {% if results.pickle_model %}
    with open('{{ results.filename_model }}', 'wb') as handle:
        # Need to unset the ``_chkfile`` attribute as it contains an open file handle which cannot be unpickled.
        mean_field_run._chkfile = None
        # Need to unset the ``opt`` attribute as it contains ctypes objects containing pointers which cannot be pickled.
        mean_field_run.opt = None
        dill.dump(mean_field_run, handle)
    {% endif %}

    sys.exit(0)
