Skip to content

Instantly share code, notes, and snippets.

@jg75
Created April 23, 2018 14:28
Show Gist options
  • Save jg75/bd3ff4fa7dd3c1a398d032ddafb664a5 to your computer and use it in GitHub Desktop.
Save jg75/bd3ff4fa7dd3c1a398d032ddafb664a5 to your computer and use it in GitHub Desktop.
A stupid experiment to see which is faster
"""A stupid experiment to see which is faster."""
import inspect
import os
import tempfile
import timeit
def get_contents_exists(path):
"""Test if the path exists and return its contents.
:param path: The path to the file
:returns contents: the file contents
"""
contents = ""
if os.path.exists(path):
contents = path.read()
path.seek(0)
return contents
def get_contents_access(path):
"""Test if the path exists and return its contents.
:param path: The path to the file
:returns contents: the file contents
"""
contents = ""
if os.access(path, os.F_OK):
contents = path.read()
path.seek(0)
return contents
def get_contents_try(path):
"""Return the contents of a file if it exists.
:param path: The path to the file
:returns contents: the file contents
"""
contents = ""
try:
contents = path.read()
path.seek(0)
except FileNotFoundError as e:
pass
return contents
def prepare():
"""Prepare to run tests. Create a temp file and write something to it.
:returns temp_file: the temporary file
"""
temp_file = tempfile.NamedTemporaryFile()
with open(__file__, 'rb') as in_file:
temp_file.write(in_file.read())
temp_file.seek(0)
return temp_file
def compare(functions, **kwargs):
"""Compare the performance of the functions.
:param functions: a tuple containing the functions to test
"""
results = list()
number = kwargs.pop("number")
message = "{0:<43} {1} operations in {2:.3f} seconds"
for function in functions:
stmt = inspect.getsource(function)
timer = timeit.Timer(stmt=stmt, **kwargs)
results.append(timer.timeit(number=number))
print(message.format(function.__name__, number, results[-1]))
def test():
"""Begin the test."""
temp_file = prepare()
functions = (
get_contents_exists,
get_contents_access,
get_contents_try
)
arguments = {
"setup": "path='{}'".format(temp_file.name),
"number": 100000000
}
for i in range(0, 2):
if os.access(temp_file.name, os.F_OK):
print("{:*^80s}".format("File exists"))
else:
print("{:*^80s}".format("File does not exist"))
compare(functions, **arguments)
if os.access(temp_file.name, os.F_OK):
temp_file.close()
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment