def stop(self) -> Session:
        """
        Stops the profiler observing, and sets :attr:`last_session`
        to the captured session.

        :return: The captured session.
        """
        if not self._active_session:
            raise RuntimeError("This profiler is not currently running.")

        try:
            get_stack_sampler().unsubscribe(self._sampler_saw_call_stack)
        except StackSampler.SubscriberNotFound:
            raise RuntimeError(
                "Failed to stop profiling. Make sure that you start/stop profiling on the same thread."
            )

        cpu_time = process_time() - self._active_session.start_process_time

        active_session = self._active_session
        self._active_session = None

        session = Session(
            frame_records=active_session.frame_records,
            start_time=active_session.start_time,
            duration=time.time() - active_session.start_time,
            min_interval=active_session.interval,
            max_interval=active_session.interval,
            sample_count=len(active_session.frame_records),
            target_description=active_session.target_description,
            start_call_stack=active_session.start_call_stack,
            cpu_time=cpu_time,
            sys_path=sys.path,
            sys_prefixes=Session.current_sys_prefixes(),
        )

        if self.last_session is not None:
            # include the previous session's data too
            session = Session.combine(self.last_session, session)

        self._last_session = session

        return session

        Stops the profiler observing, and sets :attr:`last_session`
        to the captured session.

        :return: The captured session.
        
pyinstrument/profiler.py