Смотрите на linux-ftools
. Этот комплект инструментов специально предназначен для анализа буферов и кэша. Это включает следующие инструменты:
$ fincore [options] files...
--pages=false Do not print pages
--summarize When comparing multiple files, print a summary report
--only-cached Only print stats for files that are actually in cache.
root@xxxxxx:/var/lib/mysql/blogindex# fincore --pages=false --summarize --only-cached *
stats for CLUSTER_LOG_2010_05_21.MYI: file size=93840384 , total pages=22910 , cached pages=1 , cached size=4096, cached perc=0.004365
stats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392
stats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512
stats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660
...
Примечание: В выводе в качестве примера выше, любые файлы в каталоге, /var/lib/mysql/blogindex
, это кэшируется, отображены. В этом случае существует несколько названных файлов CLUSTER_LOG_*.MYI
.
SYNTAX: filename mode [offset] [,length]
Where mode can be:
POSIX_FADV_NORMAL No further special treatment.
POSIX_FADV_RANDOM Expect random page references.
POSIX_FADV_SEQUENTIAL Expect sequential page references.
POSIX_FADV_WILLNEED Will need these pages.
POSIX_FADV_DONTNEED Dont need these pages.
POSIX_FADV_NOREUSE Data will be accessed once.
Allows an application to to tell the kernel how it expects to use a file handle,
so that the kernel can choose appropriate read-ahead and caching techniques for
access to the corresponding file. This is similar to the POSIX version of the
madvise system call, but for file access instead of memory access. The
sys_fadvise64() function is obsolete and corresponds to a broken glibc API,
sys_fadvise64_64() is the fixed version. The following are the values for the
advice parameter:
FADV_NORMAL
No special treatment.
FADV_RANDOM
Expect page references in random order.
FADV_SEQUENTIAL
Expect page references in sequential order.
FADV_WILLNEED
Expect access in the near future.
FADV_DONTNEED
Do not expect access in the near future. Subsequent access of pages in this
range will succeed, but will result either in reloading of the memory contents
from the underlying mapped file or zero-fill-in-demand pages for mappings
without an underlying file.
FADV_NOREUSE
Access data only once.
SYNTAX: fallocate file length
fallocate() allows the caller to directly manipulate the allocated disk space
for the file referred to by fd for the byte range starting at offset and
continuing for len bytes.
The mode argument determines the operation to be performed on the given
range. Currently only one flag is supported for mode:
FALLOC_FL_KEEP_SIZE
This flag allocates and initializes to zero the disk space within the range
specified by offset and len. After a successful call, subsequent writes into
this range are guaranteed not to fail because of lack of disk
space. Preallocating zeroed blocks beyond the end of the file is useful for
optimizing append workloads. Preallocating blocks does not change the file size
(as reported by stat(2)) even if it is less than offset+len.
If FALLOC_FL_KEEP_SIZE flag is not specified in mode, the default behavior is
almost same as when this flag is specified. The only difference is that on
success, the file size will be changed if offset + len is greater than the file
size. This default behavior closely resembles the behavior of the
posix_fallocate(3) library function, and is intended as a method of optimally
implementing that function.
Because allocation is done in block size chunks, fallocate() may allocate a
larger range than that which was specified.
Если Вы когда-нибудь хотите освободить его, можно использовать эту цепочку команд.
$ free && sync && echo 3 > /proc/sys/vm/drop_caches && free
total used free shared buffers cached
Mem: 1018916 980832 38084 0 46924 355764
-/+ buffers/cache: 578144 440772
Swap: 2064376 128 2064248
total used free shared buffers cached
Mem: 1018916 685008 333908 0 224 108252
-/+ buffers/cache: 576532 442384
Swap: 2064376 128 2064248
Можно предупредить, чтобы Ядро Linux отбросило различные аспекты кэшируемых элементов путем изменения числового аргумента вышеупомянутой команде.
Примечание: очистите память ненужных вещей (Kernerl 2.6.16 или более новый). Всегда удостоверяйтесь, что выполнили синхронизацию сначала для промытия полезных вещей к диску!!!
Освободить pagecache:
$ echo 1 > /proc/sys/vm/drop_caches
Освободить dentries и inodes:
$ echo 2 > /proc/sys/vm/drop_caches
Освободить pagecache, dentries и inodes:
$ echo 3 > /proc/sys/vm/drop_caches
Вышеупомянутое предназначено, чтобы быть выполненным как корень. При попытке сделать их использование sudo
затем необходимо будет изменить синтаксис немного на что-то как они:
$ sudo sh -c 'echo 1 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 2 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 3 >/proc/sys/vm/drop_caches'
Методы альтернатив к вышеупомянутому:
# alternative #1
$ sudo tee /proc/sys/vm/drop_caches <<<1
# alternative #2
$ echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh
Почему изменение в синтаксисе? /bin/echo
программа работает как корень, из-за sudo
, но оболочка, это перенаправляет вывод эха в файл только для корня, все еще работает как Вы. Ваша текущая оболочка делает перенаправление прежде sudo
запускается.
(./myprogram 1.txt; ./myprogram 2.txt; ./myprogram 3.txt; ./myprogram 4.txt) > out.txt
. Это зависит от того, что Вы хотите делать и как Ваша программа обрабатывает входные аргументы.
Но допустим, у Вас есть /путь/к/мипрограмма. sh
, которые выглядят так :
#!/bin/bash
echo "Processing file ${1?missing input file}"
Вы можете сделать следующее
find /path/to/inputfiles -name "*.txt" -exec /path/to/myprogram.sh {} \; > Out.txt
или внутри bash (или любой Bourne-подобной оболочки):
for i in *.txt; do /path/to/myprogram.sh "$i"; done > Out.txt
(Я использую for-loop или нахожу, потому что будет намного удобнее, если у Вас будет 1000 входных файлов вместо 4 файлов в Вашем примере)
myprogram-wrapper.sh:
#!/bin/sh - while test $# -ge 1 do ./myprogram $1 shift done
вызывается с помощью . /myprogram-wrapper.sh 1.txt 2.txt 3.txt 4.txt > Out.txt
Сделать многоразовую обертку:
#!/bin/sh - prog=$1 shift while test $# -ge 1 do ${prog} $1 shift done
и вызвать как обертку ./микоманда 1.txt 2.txt 3.txt 4.txt > Out.txt
Это, конечно, обманка, так как сам сценарий не является одноразовым, но я подумал, что он вам все равно может понравиться.
Очень похоже на ответ Пер, но сохраняет структуру оригинала:
{
./myprogram 1.txt
./myprogram 2.txt
./myprogram 3.txt
./myprogram 4.txt
} > Out.txt
http://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping
Я считаю это решение более элегантным:
FILE=/tmp/file.log
exec >> $FILE
./myprogram 1.txt
./myprogram 2.txt
./myprogram 3.txt
./myprogram 4.txt
exec 1<&2
echo 'Normal output has returned!'