我知道我的问题在这里有答案:QFile seek performance。但是我对答案并不完全满意。即使查看了ext4的generic_file_llseek()
的以下实现,我似乎也无法理解如何衡量复杂性。
/**
* generic_file_llseek - generic llseek implementation for regular files
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* This is a generic implemenation of ->llseek useable for all normal local
* filesystems. It just updates the file offset to the value specified by
* @offset and @origin under i_mutex.
*/
loff_t generic_file_llseek(struct file *file, loff_t offset, int origin)
{
loff_t rval;
mutex_lock(&file->f_dentry->d_inode->i_mutex);
rval = generic_file_llseek_unlocked(file, offset, origin);
mutex_unlock(&file->f_dentry->d_inode->i_mutex);
return rval;
}
/**
* generic_file_llseek_unlocked - lockless generic llseek implementation
* @file: file structure to seek on
* @offset: file offset to seek to
* @origin: type of seek
*
* Updates the file offset to the value specified by @offset and @origin.
* Locking must be provided by the caller.
*/
loff_t
generic_file_llseek_unlocked(struct file *file, loff_t offset, int origin)
{
struct inode *inode = file->f_mapping->host;
switch (origin) {
case SEEK_END:
offset += inode->i_size;
break;
case SEEK_CUR:
/*
* Here we special-case the lseek(fd, 0, SEEK_CUR)
* position-querying operation. Avoid rewriting the "same"
* f_pos value back to the file because a concurrent read(),
* write() or lseek() might have altered it
*/
if (offset == 0)
return file->f_pos;
break;
}
if (offset < 0 || offset > inode->i_sb->s_maxbytes)
return -EINVAL;
/* Special lock needed here? */
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
return offset;
}
例如,我有一个4GB的文件,并且我知道文件中间部分的偏移量,那么lseek()
如何在不遍历整个文件的情况下准确地将我带到那里?操作系统是否已经知道文件中每个字节的位置?
比如说,如果我有一个4GB的文件,我知道文件中间部分的偏移量,那么lseek()
是如何通过不遍历整个文件来精确定位的呢?操作系统是否已经知道文件中每个字节的位置?
O(1)
代码。 - hek2mgllseek
本身并没有做任何事情(除了修改一个整数)。当然,如果操作系统在中间没有预读,后续的read
可能需要先搜索已分配扇区的列表,然后可能会在机械硬盘上启动寻道,这在距离方面是O(N)。但是,lseek
也可能会_减少_旋转延迟(这是无法预测的)。 - Damon