Время старта процесса linux

Get program execution time in the shell

I want to execute something in a linux shell under a few different conditions, and be able to output the execution time of each execution. I know I could write a perl or python script that would do this, but is there a way I can do it in the shell? (which happens to be bash)

11 Answers 11

Use the built-in time keyword:

$ help time time: time [-p] PIPELINE Execute PIPELINE and print a summary of the real time, user CPU time, and system CPU time spent executing PIPELINE when it terminates. The return status is the return status of PIPELINE. The `-p' option prints the timing summary in a slightly different format. This uses the value of the TIMEFORMAT variable as the output format.
real 0m2.009s user 0m0.000s sys 0m0.004s

How is this used on a command like time -p i=x; while read line; do x=x; done < /path/to/file.txt ? It immediatly returns 0.00 unless I don't put anything before the while loop.. what gives?

@natli: While time can time an entire pipeline as-is (by virtue of being a Bash keyword), you need to use a group command ( < . ; . ; >) to time multiple commands: time -p < i=x; while read line; do x=x; done < /path/to/file.txt; >

You can get much more detailed information than the bash built-in time (i.e time(1), which Robert Gamble mentions). Normally this is /usr/bin/time .

Editor’s note: To ensure that you’re invoking the external utility time rather than your shell’s time keyword, invoke it as /usr/bin/time . time is a POSIX-mandated utility, but the only option it is required to support is -p . Specific platforms implement specific, nonstandard extensions: -v works with GNU‘s time utility, as demonstrated below (the question is tagged linux); the BSD/macOS implementation uses -l to produce similar output — see man 1 time .

Example of verbose output:

$ /usr/bin/time -v sleep 1 Command being timed: "sleep 1" User time (seconds): 0.00 System time (seconds): 0.00 Percent of CPU this job got: 1% Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05 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): 0 Average resident set size (kbytes): 0 Major (requiring I/O) page faults: 0 Minor (reclaiming a frame) page faults: 210 Voluntary context switches: 2 Involuntary context switches: 1 Swaps: 0 File system inputs: 0 File system outputs: 0 Socket messages sent: 0 Socket messages received: 0 Signals delivered: 0 Page size (bytes): 4096 Exit status: 0 

Источник

Работа с процессами в Linux

Обновлено

Обновлено: 29.03.2023 Опубликовано: 09.11.2017

Читайте также:  Установка принтера canon lbp 6020 линукс

Список процессов

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 661 0.0 0.0 4072 8 tty1 Ss+ Jul03 0:00 /sbin/mingetty
root 662 0.0 0.0 4072 8 tty2 Ss+ Jul03 0:00 /sbin/mingetty
root 16355 0.0 0.0 171636 3308 pts/0 S 15:46 0:00 sudo su
root 16366 0.0 0.0 140896 1556 pts/0 S 15:46 0:00 su
root 16368 0.0 0.0 108316 1944 pts/0 S 15:46 0:00 bash
root 18830 0.0 0.0 110244 1172 pts/0 R+ 16:20 0:00 ps u

  • USER — учетная запись пользователя, от которой запущен процесс.
  • PID — идентификатор процесса.
  • %CPU — потребление процессорного времени в процентном эквиваленте.
  • %MEM — использование памяти в процентах.
  • VSZ — Virtual Set Size. Виртуальный размер процесса (в килобайтах).
  • RSS — Resident Set Size. Размер резидентного набора (количество 1K-страниц в памяти).
  • TTY — терминал, из под которого был запущен процесс.
  • STAT — текущее состояние процесса. Могут принимать значения:
    1. R — выполнимый процесс;
    2. S — спящий;
    3. D — в состоянии подкачки на диске;
    4. T — остановлен;
    5. Z — зомби.
    6. W — не имеет резидентных страниц;
    7. < —высоко-приоритетный;
    8. N — низко-приоритетный;
    9. L — имеет страницы, заблокированные в памяти.
  • START — дата запуска процесса.
  • TIME — время запуска процесса.
  • COMMAND — команда, запустившая процесс.

Ключи

Ключ Описание
-A Все процессы.
-a Запущенные в текущем терминале, кроме главных системных.
-d Все, кроме главных системных процессов сеанса.
-e Все процессы.
f Показать дерево процессов с родителями.
T Все на конкретном терминале.
a Все, связанные с текущим терминалом и терминалами других пользователей.
r Список только работающих процессов.
x Отсоединённые от терминала.
u Показать пользователей, запустивших процесс.

Примеры

Поиск процесса с помощью grep:

Убить процесс

Останавливаем процесс по его PID:

Если процесс не завершается, убиваем его принудительно:

Остановить все процессы с именем nginx:

Как и в случае с kill, можно это сделать принудительно:

Можно остановить все процессы конкретного пользователя:

Ищем процесс по имени, извлекаем его PID и завершаем его:

kill `ps aux | grep ‘apache’ | awk »`

* обратите внимание, что запрос может вывести несколько процессов, которые будут попадать под критерии поиска — в таком случае, они будут завершены все.

Подробная информация о процессе

Для каждого процесса создается каталог по пути /proc/ , в котором создаются папки и файлы с описанием процесса.

Примеры использования /proc/

Адрес в ячейках оперативной памяти, которые занял процесс:

Команда, которой был запущен процесс:

Символьная ссылка на рабочий каталог процесса:

Символьная ссылка на исполняемый файл, запустивший процесс:

Увидеть ссылки на дескрипторы открытых файлов, которые затрагивает процесс:

Подробное описание на сайте man7.org.

Потребление ресурсов процессами

Для просмотра статистики потребления ресурсов используем утилиту top:

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
21059 root 20 0 157884 2280 1496 R 18,8 0,1 0:00.03 top
1 root 20 0 190996 2964 1652 S 0,0 0,1 6:49.99 systemd
2 root 20 0 0 0 0 S 0,0 0,0 0:01.78 kthreadd
3 root 20 0 0 0 0 S 0,0 0,0 0:24.75 ksoftirqd/0
5 root 0 -20 0 0 0 S 0,0 0,0 0:00.00 kworker/0:0H

  • PID — идентификатор процесса.
  • USER — имя учетной записи, от которой запущен процесс.
  • PR — приоритет процесса.
  • NI — приоритет, выставленной командой nice.
  • VIRT — объем виртуальной памяти, потребляемый процессом.
  • RES — объем используемой оперативной памяти.
  • SHR — количество разделяемой памяти, которое используется процессом.
  • S — состояние процесса.
  • %CPU — процент использования процессорного времени.
  • %MEM — потребление оперативной памяти в процентах.
  • TIME — использование процессорного времени в секундах.
  • COMMAND — команда, которая запустила процесс.

Источник

Читайте также:  Linux alias with parameter

start time of a process on linux

How to find a process start time on ubuntu linux machine using c language. In linux there is /proc/[pid]/stat file which give information starttime %lu /*The time in jiffies the process started after system boot*/
and file /proc/stat that gives

btime %lu /*measurement of system boot time since Epoch in seconds*/ 

For adding both these values how can I convert former value into seconds because it is in jiffies unit.

1 Answer 1

Jiffies per second is configurable when one compiles the Linux kernel.

The following program uses the number of jiffies per second on the kernel you’re running. It takes an optional command line parameter, which is the process number. The default is the process number of the running program itself. Each second, it outputs the start time of the specified process, both as local time and UTC. The only reason for the repeat loop is to demonstrate that the value doesn’t change.

#include #include #include #include #include #include #include #include int find_nth_space(char *search_buffer, int space_ordinality ) < int jndex; int space_count; space_count=0; for(jndex=0; search_buffer[jndex]; jndex++ ) < if(search_buffer[jndex]==' ') < space_count++; if(space_count>=space_ordinality) < return jndex; >> > fprintf(stderr,"looking for too many spaces\n"); exit(1); > /* find_nth_space() */ int main(int argc, char **argv ) < int field_begin; int stat_fd; char proc_buf[80]; char stat_buf[2048]; long jiffies_per_second; long long boot_time_since_epoch; long long process_start_time_since_boot; time_t process_start_time_since_epoch; ssize_t read_result; struct tm gm_buf; struct tm local_buf; jiffies_per_second=sysconf(_SC_CLK_TCK); if(argc<2) < strcpy(proc_buf,"/proc/self/stat"); >else < sprintf(proc_buf,"/proc/%ld/stat",strtol(argv[1],NULL,0)); >for(;;) < stat_fd=open(proc_buf,O_RDONLY); if(stat_fd<0) < fprintf(stderr,"open() fail\n"); exit(1); >read_result=read(stat_fd,stat_buf,sizeof(stat_buf)); if(read_result <0) < fprintf(stderr,"read() fail\n"); exit(1); >if(read_result>=sizeof(stat_buf)) < fprintf(stderr,"stat_buf is too small\n"); exit(1); >field_begin=find_nth_space(stat_buf,21)+1; stat_buf[find_nth_space(stat_buf,22)]=0; sscanf(stat_buf+field_begin,"%llu",&process_start_time_since_boot); close(stat_fd); stat_fd=open("/proc/stat",O_RDONLY); if(stat_fd <0) < fprintf(stderr,"open() fail\n"); exit(1); >read_result=read(stat_fd,stat_buf,sizeof(stat_buf)); if(read_result <0) < fprintf(stderr,"read() fail\n"); exit(1); >if(read_result>=sizeof(stat_buf)) < fprintf(stderr,"stat_buf is too small\n"); exit(1); >close(stat_fd); field_begin=strstr(stat_buf,"btime ")-stat_buf+6; sscanf(stat_buf+field_begin,"%llu",&boot_time_since_epoch); process_start_time_since_epoch = boot_time_since_epoch+process_start_time_since_boot/jiffies_per_second; localtime_r(&process_start_time_since_epoch,&local_buf); gmtime_r (&process_start_time_since_epoch,&gm_buf ); printf("local time: %02d:%02d:%02d\n", local_buf.tm_hour, local_buf.tm_min, local_buf.tm_sec ); printf("UTC: %02d:%02d:%02d\n", gm_buf.tm_hour, gm_buf.tm_min, gm_buf.tm_sec ); sleep(1); > return 0; > /* main() */ 

Источник

How to get the start time of a long-running Linux process?

Is it possible to get the start time of an old running process? It seems that ps will report the date (not the time) if it wasn’t started today, and only the year if it wasn’t started this year. Is the precision lost forever for old processes?

Читайте также:  Spider man на linux

Is there anything wrong with using ps -p -o lstart ? Seems like it works, but I’m not sure why it’s not the immediate obvious answer for the many times this question seems to come up.

@ajwood It would be better to use ps -p -o lstart= to avoid additional line (header) to be printed.

Is there anything wrong with using ps -p -o lstart ? Maybe the fact there’s no lstart neither in 2004 Edition nor in 2013 Edition of POSIX 1003.1 standard?

@PiotrDobrogost, that would be a problem if the question asked about POSIX, but it’s asking about Linux.

Mods — techraf, Makyen, David Rawson, Tsyvarev, Paul Roub — why don’t you move it to a more appropriate site such as StackExchange or Superuser instead of closing the question? This is a good and useful question

8 Answers 8

You can specify a formatter and use lstart , like this command:

The above command will output all processes, with formatters to get PID, command run, and date+time started.

Example (from Debian/Jessie command line)

$ ps -eo pid,lstart,cmd PID CMD STARTED 1 Tue Jun 7 01:29:38 2016 /sbin/init 2 Tue Jun 7 01:29:38 2016 [kthreadd] 3 Tue Jun 7 01:29:38 2016 [ksoftirqd/0] 5 Tue Jun 7 01:29:38 2016 [kworker/0:0H] 7 Tue Jun 7 01:29:38 2016 [rcu_sched] 8 Tue Jun 7 01:29:38 2016 [rcu_bh] 9 Tue Jun 7 01:29:38 2016 [migration/0] 10 Tue Jun 7 01:29:38 2016 [kdevtmpfs] 11 Tue Jun 7 01:29:38 2016 [netns] 277 Tue Jun 7 01:29:38 2016 [writeback] 279 Tue Jun 7 01:29:38 2016 [crypto] . 

You can read ps ‘s manpage or check Opengroup’s page for the other formatters.

Be aware that lstart time can change, the stat methods below are safer — unix.stackexchange.com/questions/274610/….

The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart which always gives the full date and time the process started:

# ps -p 1 -wo pid,lstart,cmd PID STARTED CMD 1 Mon Dec 23 00:31:43 2013 /sbin/init # ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd USER PID %CPU %MEM VSZ RSS TT STAT STARTED CMD root 1 0.0 0.1 2800 1152 ? Ss Mon Dec 23 00:31:44 2013 /sbin/init root 5151 0.3 0.1 4732 1980 pts/2 S Sat Mar 8 16:50:47 2014 bash 

(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:

# date; ls -ld /proc/1 /proc/$$ Sat Mar 8 17:14:21 EST 2014 dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1 dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151 

Note that in this case I ran a «ps -p 1» command at about 16:50, then spawned a new bash shell, then ran the «ps -p 1 -p $$» command within that shell shortly afterward. )

Источник

Оцените статью
Adblock
detector