Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
performance
#2
from datetime import datetime
import struct
import timeit

def convert_1(qdate, qtime):
    return str(datetime.strptime(qdate + qtime, '%d%m%y%H%M%S'))

def convert_2(qdate, qtime):
    day = qdate[:2]
    month = qdate[2:4]
    year = f'20{qdate[4:]}' #'20{}'.format(qdate[4:])
    hour = qtime[:2]
    minute = qtime[2:4]
    second = qtime[4:]
    return f'20{year}-{month}-{day} {hour}:{minute}:{second}' #return '{}-{}-{} {}:{}:{}'.format(year, month, day, hour, minute, second)

def convert_3(qdate, qtime):
        fmt_string = '2s2s2s'
        # converts unicode input to byte string and results back to unicode string
        field_struct = struct.Struct(fmt_string)
        unpack = field_struct.unpack_from
        parse = lambda line: tuple(s.decode().strip() for s in unpack(line.encode()))
        year, month, day  = parse(qdate)
        hour, minute, second = parse(qtime)
        return f'20{year}-{month}-{day} {hour}:{minute}:{second}'

print(timeit.timeit('convert_1("021020", "010000")', setup='from __main__ import convert_1', number=100000))
print(timeit.timeit('convert_2("021020", "010000")', setup='from __main__ import convert_2', number=100000))
print(timeit.timeit('convert_3("021020", "010000")', setup='from __main__ import convert_3', number=100000))
with your implementation in coonvert_2:
Output:
1.4443583 0.15659809999999985 0.3793516000000001
with f-strings
Output:
1.468083 0.10396260000000002 0.3841863000000001
yes, it looks it's the fastest one
You can gain slightly more if you use f-strings
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
performance - by kerzol81 - Oct-07-2019, 09:30 AM
RE: performance - by buran - Oct-07-2019, 10:19 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020