does the base of a seek operation affect how fast it runs, or is it just how some standard offset is computed?

StackOverflow https://stackoverflow.com/questions/17515231

  •  02-06-2022
  •  | 
  •  

Question

Eg, in python, is this:

with open('myfile', 'rb') as f:
  f.seek(0, 2)  # seek to EOF
  file_size = f.tell()

  f.seek(file_size - 10)
  print f.read(10)

  f.seek(file_size - 20)
  print f.read(10)

  f.seek(file_size - 30)
  print f.read(10)
  ...

any less efficient than this:

with open('myfile', 'rb') as f:
  f.seek(-10, 2)
  print f.read(10)

  f.seek(-20, 1)
  print f.read(10)

  f.seek(-20, 1)
  print f.read(10)
  ...
Was it helpful?

Solution

The read position in a file is a simple index maintained by the OS kernel; there is no physical head movements involved.

The C code subtracting 10 from the current position or you calculating the new position in python will make very little difference.

OTHER TIPS

Note that the programs are not identical since read moves the cursor position! So you want to call f.seek(-20, 1) unless you want to read the same 10 bytes over and over.

Also, the additional call to ftell may make the first one (imperceptibly) slower. Another difference between your programs is that they behave slightly differently if the file is being written to while you're reading it.

Also note that you can directly seek from EOF, like this:

with open('myfile', 'rb') as f:
    f.seek(-10, 2) # Seek from EOF
    print(f.read(10))

    f.seek(-20, 1)
    print(f.read(10))

    f.seek(-20, 1)
    print(f.read(10))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top