Can This Code Be Made Faster?

Sean Ross sross at connectmail.carleton.ca
Fri Sep 12 09:56:53 EDT 2003


"Ganesan R" <rganesan at myrealbox.com> wrote in message
news:ou1xumz4s0.fsf at andlx-anamika.cisco.com...
> >>>>> "John" == John Abel <john.abel at pa.press.net> writes:
[snip]
> ======
> fileTimes = []
> for fileName in fileList:
>     try:
>         fileTimes.append(
>             (os.lstat(os.path.join(rootPath, fileName)).st_mtime,
fileName)
>         )
>     except:
>         pass
>
> ======



def getFileTimes(fileList, rootPath):
    # using a function can speed things up (I seem to recall)
    fileTimes = []
    # use aliases to save some look-up time inside loop
    append = fileTimes.append; lstat = os.lstat; joinPath = os.path.join;
    for fileName in fileList:
        try:
            append((lstat(joinPath(rootPath, fileName)).st_mtime, fileName))
        except OSError:
            pass
    return fileTimes


I don't know if function composition would help speed (you'd have to
timeit.py),
but it might help readability:

# from "Python Cookbook", pg. 467
def compose(f, g, *orig_args, **orig_kwds):
    def nested_function(*more_args, **more_kwds):
        return f(g(*more_args, **more_kwds), *orig_args, **orig_kwds)
    return nested_function

def getFileTimes2(fileList, rootPath):
    fileTimes = []
    append = fileTimes.append
    lstat = compose(os.lstat, os.path.join)
    for fileName in fileList:
        try:
            append( (lstat(rootPath, fileName).st_mtime, fileName) )
        except OSError:
            pass
    return fileTimes


HTH
Sean






More information about the Python-list mailing list