o
    1&i                     @  s   d Z ddlmZ ddlZddlZddlZddlmZmZ zddl	Z	dZ
W n ey/   dZ
Y nw e
Zdd	d
ZdddZG dd dZdS )a  
Memory monitoring utilities for measuring memory usage.

Example usage:
    tracker = MemoryTracker("my_function")
    with tracker.monitor():
        my_function()
    # Access data: tracker.rss_delta, tracker.duration, etc.
    # Get formatted string: tracker.get_summary()
    )annotationsN)DictOptionalTFreturnOptional[int]c                  C  s.   t rzt } | jW S  ty   Y dS w dS )z
    Get current available system memory in bytes.

    Used for memory threshold checking in parallel test execution.

    Returns:
        int or None: Available memory in bytes, or None if unavailable
    N)_HAS_PSUTILpsutilvirtual_memory	available	Exception)sys_mem r   AC:\wamp64\www\opt\env\Lib\site-packages\numba/misc/memoryutils.pyget_available_memory   s   	r   Dict[str, Optional[int]]c               	   C  s~   i } t r-ztt }| }|j| d< t }|j| d< W n tj	tj
fy,   Y nw d| vr5d| d< d| vr=d| d< | S )a^  
    Get memory usage information needed for monitoring.

    Returns only RSS and available memory which are the fields
    actually used by the MemoryTracker.

    Returns:
        dict: Memory usage information including:
            - rss: Current process RSS (physical memory currently used)
            - available: Available system memory
    rssr
   N)r   r   Processosgetpidmemory_infor   r	   r
   ZNoSuchProcessZAccessDenied)r   processZmem_infor   r   r   r   get_memory_usage/   s    
r   c                   @  st   e Zd ZU dZded< ded< ded< ded< d	ed
< d	ed< ded< ded< dddZejdd ZdddZ	dS )MemoryTrackerz
    A simple memory monitor that tracks RSS delta and timing.

    Stores monitoring data in instance attributes for later access.
    Each instance is typically used for monitoring a single operation.
    intpidstrnamezfloat | None
start_timeend_timezDict[str, int | None] | Nonestart_memory
end_memorydurationz
int | None	rss_deltac                 C  s8   t  | _|| _d| _d| _d| _d| _d| _d| _	dS )z6Initialize a MemoryTracker with empty monitoring data.N)
r   r   r   r   r   r   r   r    r!   r"   )selfr   r   r   r   __init__d   s   

zMemoryTracker.__init__c              
   c  s    t   | _t | _z2| V  W t   | _t | _| j| j | _| jdd}| jdd}|r8|r8|| | _dS d| _dS t   | _t | _| j| j | _| jdd}| jdd}|re|re|| | _w d| _w )a  
        Context manager to monitor memory usage during function execution.

        Records start/end memory usage and timing, calculates RSS delta,
        and stores all data in instance attributes.

        Args:
            name (str): Name/identifier for the function or operation being
                        monitored

        Yields:
            self: The MemoryTracker instance for accessing stored data
        r   r   N)	timer   r   r   r   r    r!   getr"   )r#   	start_rssend_rssr   r   r   monitoro   s6   


zMemoryTracker.monitorr   c                 C  s   | j du s
| jdu rtd| jd}ddd}tdt| j}| j dd	}| jdd	}d
| j d| j	 d| d| j
ddd|| d|| d|| jdd d|| g}d|S )a  
        Return a formatted summary of the memory monitoring data.

        Formats the stored monitoring data into a human-readable string
        containing name, PID, RSS delta, available memory, duration,
        and start time.

        Returns:
            str: Formatted summary string with monitoring results

        Note:
            Should be called after monitor() context has completed
            to ensure all data is available.
        Nz$Memory monitoring data not availabler
   Fc                 S  sz   | du rdS | dkrdS d}|r| dk rdnd}t | } dD ]}| d	k r0| | d
d|   S | d	 } q| | d
dS )z&Convert bytes to human readable formatNzN/Ar   z0 B -+)BZKBMBGBg      @z.2f z TB)abs)Z	bytes_val	show_signsignunitr   r   r   format_bytes   s   
z/MemoryTracker.get_summary.<locals>.format_bytesz%H:%M:%Sr   r   zName: zPID: zStart: z
Duration: z.3fszStart RSS: z	End RSS: zRSS delta: T)r2   zAvail memory: z | )F)r   r    
ValueErrorr&   r%   strftime	localtimer   r   r   r!   r"   join)r#   Zcurrent_availabler5   Zstart_tsr'   r(   bufr   r   r   get_summary   s"   




zMemoryTracker.get_summaryN)r   r   )r   r   )
__name__
__module____qualname____doc____annotations__r$   
contextlibcontextmanagerr)   r<   r   r   r   r   r   T   s   
 

 r   )r   r   )r   r   )r@   
__future__r   r   rB   r%   typingr   r   r   r   ImportErrorZIS_SUPPORTEDr   r   r   r   r   r   r   <module>   s     


%