tkrajina/gpxpy

Processing time of format_time() in gpxfield.py

ekspla opened this issue · 1 comments

I found that the processing time in serializing xml can be reduced by ~10 % in my test case (of about 13k trackpoints, from 1.4 to 1.2 seconds by cProfile) if we avoid using datetime.strftime().

ORIGINAL (gpxfield.py:91):

def format_time(time: mod_datetime.datetime) -> str:
    offset = time.utcoffset()
    if not offset:
        tz = 'Z'
    else:
        tz = time.strftime('%z')
    if time.microsecond:
        ms = time.strftime('.%f')
    else:
        ms = ''
    return ''.join((time.strftime('%Y-%m-%dT%H:%M:%S'), ms, tz))

1:

def format_time(time: mod_datetime.datetime) -> str:
    offset = time.utcoffset()
    if not offset:
        tz = 'Z'
    else:
        tz = time.strftime('%z')
    isofmt_time = time.replace(tzinfo=None).isoformat()
    return ''.join((isofmt_time, tz))

If we can accept a TZ offset format with additional colon, such as '+09:00', the code can be much simpler and slightly faster, even more. This format is also allowed in the standard but is slightly different from the ORIGINAL one ('+0900').

2:

def format_time(time: mod_datetime.datetime) -> str:
    isofmt_time = time.isoformat().replace('+00:00', 'Z')
    return isofmt_time
ekspla commented

Case closed because the PR is merged.