您可以尝试使用 fadvice 和 madvice,但不能保证。两者都更可能适用于更大的文件/数据,因为:


部分页面是故意保留的,因为期望保留需要的内存比丢弃不需要的内存要好。


查看 linux 源代码,什么会做什么,什么不会。例如 POSIX_FADV_NOREUSE 不做任何事情。


http://lxr.free-electrons.com/source/mm/fadvise.c#L62


http://lxr.free-electrons.com/source/mm/madvise.c


package main


import "fmt"

import "os"

import "syscall"


import "golang.org/x/sys/unix"


func main() {

    advise := false

    if len(os.Args) > 1 && os.Args[1] == "-x" {

        fmt.Println("setting file advise")

        advise =true

    }


    data := make([]byte, 100)

    handler, err := os.Open("Foo.txt")

    if err != nil {

        fmt.Println("Failed on open: ", err)

    }; defer handler.Close()


    if advise {

        unix.Fadvise(int(handler.Fd()), 0, 0, 4) // 4 == POSIX_FADV_DONTNEED

    }


    read, err := handler.Read(data)

    if err != nil {

        fmt.Println("Failed on read: ", err)

        os.Exit(1)

    }


    if advise {

        syscall.Madvise(data, 4) // 4 == MADV_DONTNEED

    }


    fmt.Printf("read %v bytes\n", read)

}

/usr/bin/time -v ./direct -x


Command being timed: "./direct -x"

User time (seconds): 0.00

System time (seconds): 0.00

Percent of CPU this job got: 0%

Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03

Average shared text size (kbytes): 0

Average unshared data size (kbytes): 0

Average stack size (kbytes): 0

Average total size (kbytes): 0

Maximum resident set size (kbytes): 1832

Average resident set size (kbytes): 0

Major (requiring I/O) page faults: 2

Minor (reclaiming a frame) page faults: 149

Voluntary context switches: 2

Involuntary context switches: 2

Swaps: 0

File system inputs: 200

File system outputs: 0

Socket messages sent: 0

Socket messages received: 0

Signals delivered: 0

Page size (bytes): 4096

Exit status: 0