Invokes the block with a Benchmark::Report object, which may be used to collect and report on the results of individual benchmark tests. Reserves label_width
leading spaces for labels on each line. Prints caption
at the top of the report, and uses format
to format each line. (Note: caption
must contain a terminating newline character, see the default Benchmark::Tms::CAPTION for an example.)
Returns an array of Benchmark::Tms
objects.
If the block returns an array of Benchmark::Tms
objects, these will be used to format additional lines of output. If labels
parameter are given, these are used to label these extra lines.
Note: Other methods provide a simpler interface to this one, and are suitable for nearly all benchmarking requirements. See the examples in Benchmark
, and the bm
and bmbm
methods.
Example:
require 'benchmark' include Benchmark # we need the CAPTION and FORMAT constants n = 5000000 Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x| tf = x.report("for:") { for i in 1..n; a = "1"; end } tt = x.report("times:") { n.times do ; a = "1"; end } tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } [tf+tt+tu, (tf+tt+tu)/3] end
Generates:
user system total real for: 0.970000 0.000000 0.970000 ( 0.970493) times: 0.990000 0.000000 0.990000 ( 0.989542) upto: 0.970000 0.000000 0.970000 ( 0.972854) >total: 2.930000 0.000000 2.930000 ( 2.932889) >avg: 0.976667 0.000000 0.976667 ( 0.977630)
Retrieve the PathSupport
object that RubyGems uses to lookup files.
Initialize the filesystem paths to use from env
. env
is a hash-like object (typically ENV
) that is queried for ‘GEM_HOME’, ‘GEM_PATH’, and ‘GEM_SPEC_CACHE’ Keys for the env
hash should be Strings, and values of the hash should be Strings or nil
.
Returns a 9-element array representing the parts of the URI formed from the string uri
; each array element is a string or nil
:
names = %w[scheme userinfo host port registry path opaque query fragment] values = URI.split('https://john.doe@www.example.com:123/forum/questions/?tag=networking&order=newest#top') names.zip(values) # => [["scheme", "https"], ["userinfo", "john.doe"], ["host", "www.example.com"], ["port", "123"], ["registry", nil], ["path", "/forum/questions/"], ["opaque", nil], ["query", "tag=networking&order=newest"], ["fragment", "top"]]
Splits a string into an array of tokens in the same way the UNIX Bourne shell does.
argv = Shellwords.split('here are "two words"') argv #=> ["here", "are", "two words"]
line
must not contain NUL characters because of nature of exec
system call.
Note, however, that this is not a command line parser. Shell metacharacters except for the single and double quotes and backslash are not treated as such.
argv = Shellwords.split('ruby my_prog.rb | less') argv #=> ["ruby", "my_prog.rb", "|", "less"]
String#shellsplit
is a shortcut for this function.
argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]
Splits a string into an array of tokens in the same way the UNIX Bourne shell does.
argv = Shellwords.split('here are "two words"') argv #=> ["here", "are", "two words"]
line
must not contain NUL characters because of nature of exec
system call.
Note, however, that this is not a command line parser. Shell metacharacters except for the single and double quotes and backslash are not treated as such.
argv = Shellwords.split('ruby my_prog.rb | less') argv #=> ["ruby", "my_prog.rb", "|", "less"]
String#shellsplit
is a shortcut for this function.
argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]
Returns a topologically sorted array of nodes. The array is sorted from children to parents, i.e. the first element has no child and the last node has no parent.
If there is a cycle, TSort::Cyclic
is raised.
class G include TSort def initialize(g) @g = g end def tsort_each_child(n, &b) @g[n].each(&b) end def tsort_each_node(&b) @g.each_key(&b) end end graph = G.new({1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]}) p graph.tsort #=> [4, 2, 3, 1] graph = G.new({1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}) p graph.tsort # raises TSort::Cyclic
Returns a topologically sorted array of nodes. The array is sorted from children to parents, i.e. the first element has no child and the last node has no parent.
The graph is represented by each_node and each_child. each_node should have call
method which yields for each node in the graph. each_child should have call
method which takes a node argument and yields for each child node.
If there is a cycle, TSort::Cyclic
is raised.
g = {1=>[2, 3], 2=>[4], 3=>[2, 4], 4=>[]} each_node = lambda {|&b| g.each_key(&b) } each_child = lambda {|n, &b| g[n].each(&b) } p TSort.tsort(each_node, each_child) #=> [4, 2, 3, 1] g = {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]} each_node = lambda {|&b| g.each_key(&b) } each_child = lambda {|n, &b| g[n].each(&b) } p TSort.tsort(each_node, each_child) # raises TSort::Cyclic
Returns the principal (non-negative) square root of x
.
Domain: [0, INFINITY]
.
Range: [0, INFINITY]
.
Examples:
sqrt(0.0) # => 0.0 sqrt(0.5) # => 0.7071067811865476 sqrt(1.0) # => 1.0 sqrt(2.0) # => 1.4142135623730951 sqrt(4.0) # => 2.0 sqrt(9.0) # => 3.0 sqrt(INFINITY) # => Infinity
Returns the cube root of x
.
Domain: [-INFINITY, INFINITY]
.
Range: [-INFINITY, INFINITY]
.
Examples:
cbrt(-INFINITY) # => -Infinity cbrt(-27.0) # => -3.0 cbrt(-8.0) # => -2.0 cbrt(-2.0) # => -1.2599210498948732 cbrt(1.0) # => 1.0 cbrt(0.0) # => 0.0 cbrt(1.0) # => 1.0 cbrt(2.0) # => 1.2599210498948732 cbrt(8.0) # => 2.0 cbrt(27.0) # => 3.0 cbrt(INFINITY) # => Infinity
Creates a new child process by doing one of the following in that process:
Passing string command_line
to the shell.
Invoking the executable at exe_path
.
This method has potential security vulnerabilities if called with untrusted input; see Command Injection.
Returns the process ID (pid) of the new process, without waiting for it to complete.
To avoid zombie processes, the parent process should call either:
Process.wait
, to collect the termination statuses of its children.
Process.detach
, to register disinterest in their status.
The new process is created using the exec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).
Argument env
, if given, is a hash that affects ENV
for the new process; see Execution Environment.
Argument options
is a hash of options for the new process; see Execution Options.
The first required argument is one of the following:
command_line
if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.
exe_path
otherwise.
Argument command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
spawn('if true; then echo "Foo"; fi') # => 798847 # Shell reserved word. Process.wait # => 798847 spawn('exit') # => 798848 # Built-in. Process.wait # => 798848 spawn('date > /tmp/date.tmp') # => 798879 # Contains meta character. Process.wait # => 798849 spawn('date > /nop/date.tmp') # => 798882 # Issues error message. Process.wait # => 798882
The command line may also contain arguments and options for the command:
spawn('echo "Foo"') # => 799031 Process.wait # => 799031
Output:
Foo
See Execution Shell for details about the shell.
Raises an exception if the new process could not execute.
Argument exe_path
Argument exe_path
is one of the following:
The string path to an executable to be called.
A 2-element array containing the path to an executable to be called, and the string to be used as the name of the executing process.
spawn('/usr/bin/date') # Path to date on Unix-style system. Process.wait
Output:
Mon Aug 28 11:43:10 AM CDT 2023
Ruby invokes the executable directly. This form does not use the shell; see Arguments args for caveats.
If one or more args
is given, each is an argument or option to be passed to the executable:
spawn('echo', 'C*') # => 799392 Process.wait # => 799392 spawn('echo', 'hello', 'world') # => 799393 Process.wait # => 799393
Output:
C* hello world
Raises an exception if the new process could not execute.
Exits the process immediately; no exit handlers are called. Returns exit status status
to the underlying operating system.
Process.exit!(true)
Values true
and false
for argument status
indicate, respectively, success and failure; The meanings of integer values are system-dependent.
Initiates termination of the Ruby script by raising SystemExit
; the exception may be caught. Returns exit status status
to the underlying operating system.
Values true
and false
for argument status
indicate, respectively, success and failure; The meanings of integer values are system-dependent.
Example:
begin exit puts 'Never get here.' rescue SystemExit puts 'Rescued a SystemExit exception.' end puts 'After begin block.'
Output:
Rescued a SystemExit exception. After begin block.
Just prior to final termination, Ruby executes any at-exit procedures (see Kernel::at_exit) and any object finalizers (see ObjectSpace::define_finalizer
).
Example:
at_exit { puts 'In at_exit function.' } ObjectSpace.define_finalizer('string', proc { puts 'In finalizer.' }) exit
Output:
In at_exit function. In finalizer.
Terminates execution immediately, effectively by calling Kernel.exit(false)
.
If string argument msg
is given, it is written to STDERR prior to termination; otherwise, if an exception was raised, prints its message and backtrace.
Waits for a suitable child process to exit, returns its process ID, and sets $?
to a Process::Status
object containing information on that process. Which child it waits for depends on the value of the given pid
:
Positive integer: Waits for the child process whose process ID is pid
:
pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 230866 pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 230891 Process.wait(pid0) # => 230866 $? # => #<Process::Status: pid 230866 exit 13> Process.wait(pid1) # => 230891 $? # => #<Process::Status: pid 230891 exit 14> Process.wait(pid0) # Raises Errno::ECHILD
0
: Waits for any child process whose group ID is the same as that of the current process:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." end retrieved_pid = Process.wait(0) puts "Process.wait(0) returned pid #{retrieved_pid}, which is child 0 pid." begin Process.wait(0) rescue Errno::ECHILD => x puts "Raised #{x.class}, because child 1 process group ID differs from parent process group ID." end
Output:
Parent process group ID is 225764. Child 0 pid is 225788 Child 0 process group ID is 225764 (same as parent's). Child 1 pid is 225789 Child 1 process group ID is 225789 (different from parent's). Process.wait(0) returned pid 225788, which is child 0 pid. Raised Errno::ECHILD, because child 1 process group ID differs from parent process group ID.
-1
(default): Waits for any child process:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." sleep 3 # To force child 1 to exit later than child 0 exit. end child_pids = [child0_pid, child1_pid] retrieved_pid = Process.wait(-1) puts child_pids.include?(retrieved_pid) retrieved_pid = Process.wait(-1) puts child_pids.include?(retrieved_pid)
Output:
Parent process group ID is 228736. Child 0 pid is 228758 Child 0 process group ID is 228736 (same as parent's). Child 1 pid is 228759 Child 1 process group ID is 228759 (different from parent's). true true
Less than -1
: Waits for any child whose process group ID is -pid
:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." end sleep 1 retrieved_pid = Process.wait(-child1_pid) puts "Process.wait(-child1_pid) returned pid #{retrieved_pid}, which is child 1 pid." begin Process.wait(-child1_pid) rescue Errno::ECHILD => x puts "Raised #{x.class}, because there's no longer a child with process group id #{child1_pid}." end
Output:
Parent process group ID is 230083. Child 0 pid is 230108 Child 0 process group ID is 230083 (same as parent's). Child 1 pid is 230109 Child 1 process group ID is 230109 (different from parent's). Process.wait(-child1_pid) returned pid 230109, which is child 1 pid. Raised Errno::ECHILD, because there's no longer a child with process group id 230109.
Argument flags
should be given as one of the following constants, or as the logical OR of both:
Process::WNOHANG
: Does not block if no child process is available.
Process::WUNTRACED
: May return a stopped child process, even if not yet reported.
Not all flags are available on all platforms.
Raises Errno::ECHILD if there is no suitable child process.
Not available on all platforms.
Process.waitpid
is an alias for Process.wait
.
Like Process.waitpid
, but returns an array containing the child process pid
and Process::Status
status
:
pid = Process.spawn('ruby', '-e', 'exit 13') # => 309581 Process.wait2(pid) # => [309581, #<Process::Status: pid 309581 exit 13>]
Process.waitpid2
is an alias for Process.wait2
.
Waits for a suitable child process to exit, returns its process ID, and sets $?
to a Process::Status
object containing information on that process. Which child it waits for depends on the value of the given pid
:
Positive integer: Waits for the child process whose process ID is pid
:
pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 230866 pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 230891 Process.wait(pid0) # => 230866 $? # => #<Process::Status: pid 230866 exit 13> Process.wait(pid1) # => 230891 $? # => #<Process::Status: pid 230891 exit 14> Process.wait(pid0) # Raises Errno::ECHILD
0
: Waits for any child process whose group ID is the same as that of the current process:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." end retrieved_pid = Process.wait(0) puts "Process.wait(0) returned pid #{retrieved_pid}, which is child 0 pid." begin Process.wait(0) rescue Errno::ECHILD => x puts "Raised #{x.class}, because child 1 process group ID differs from parent process group ID." end
Output:
Parent process group ID is 225764. Child 0 pid is 225788 Child 0 process group ID is 225764 (same as parent's). Child 1 pid is 225789 Child 1 process group ID is 225789 (different from parent's). Process.wait(0) returned pid 225788, which is child 0 pid. Raised Errno::ECHILD, because child 1 process group ID differs from parent process group ID.
-1
(default): Waits for any child process:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." sleep 3 # To force child 1 to exit later than child 0 exit. end child_pids = [child0_pid, child1_pid] retrieved_pid = Process.wait(-1) puts child_pids.include?(retrieved_pid) retrieved_pid = Process.wait(-1) puts child_pids.include?(retrieved_pid)
Output:
Parent process group ID is 228736. Child 0 pid is 228758 Child 0 process group ID is 228736 (same as parent's). Child 1 pid is 228759 Child 1 process group ID is 228759 (different from parent's). true true
Less than -1
: Waits for any child whose process group ID is -pid
:
parent_pgpid = Process.getpgid(Process.pid) puts "Parent process group ID is #{parent_pgpid}." child0_pid = fork do puts "Child 0 pid is #{Process.pid}" child0_pgid = Process.getpgid(Process.pid) puts "Child 0 process group ID is #{child0_pgid} (same as parent's)." end child1_pid = fork do puts "Child 1 pid is #{Process.pid}" Process.setpgid(0, Process.pid) child1_pgid = Process.getpgid(Process.pid) puts "Child 1 process group ID is #{child1_pgid} (different from parent's)." end sleep 1 retrieved_pid = Process.wait(-child1_pid) puts "Process.wait(-child1_pid) returned pid #{retrieved_pid}, which is child 1 pid." begin Process.wait(-child1_pid) rescue Errno::ECHILD => x puts "Raised #{x.class}, because there's no longer a child with process group id #{child1_pid}." end
Output:
Parent process group ID is 230083. Child 0 pid is 230108 Child 0 process group ID is 230083 (same as parent's). Child 1 pid is 230109 Child 1 process group ID is 230109 (different from parent's). Process.wait(-child1_pid) returned pid 230109, which is child 1 pid. Raised Errno::ECHILD, because there's no longer a child with process group id 230109.
Argument flags
should be given as one of the following constants, or as the logical OR of both:
Process::WNOHANG
: Does not block if no child process is available.
Process::WUNTRACED
: May return a stopped child process, even if not yet reported.
Not all flags are available on all platforms.
Raises Errno::ECHILD if there is no suitable child process.
Not available on all platforms.
Process.waitpid
is an alias for Process.wait
.
Like Process.waitpid
, but returns an array containing the child process pid
and Process::Status
status
:
pid = Process.spawn('ruby', '-e', 'exit 13') # => 309581 Process.wait2(pid) # => [309581, #<Process::Status: pid 309581 exit 13>]
Process.waitpid2
is an alias for Process.wait2
.
Waits for all children, returns an array of 2-element arrays; each subarray contains the integer pid and Process::Status
status for one of the reaped child processes:
pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 325470 pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 325495 Process.waitall # => [[325470, #<Process::Status: pid 325470 exit 13>], [325495, #<Process::Status: pid 325495 exit 14>]]
Notify the Ruby virtual machine that the boot sequence is finished, and that now is a good time to optimize the application. This is useful for long running applications.
This method is expected to be called at the end of the application boot. If the application is deployed using a pre-forking model, Process.warmup
should be called in the original process before the first fork.
The actual optimizations performed are entirely implementation specific and may change in the future without notice.
On CRuby, Process.warmup
:
Performs a major GC
.
Compacts the heap.
Promotes all surviving objects to the old generation.
Precomputes the coderange of all strings.
Frees all empty heap pages and increments the allocatable pages counter by the number of pages freed.
Invoke malloc_trim
if available to free empty malloc pages.
Returns a 2-element array of the current (soft) limit and maximum (hard) limit for the given resource
.
Argument resource
specifies the resource whose limits are to be returned; see Process.setrlimit
.
Each of the returned values cur_limit
and max_limit
is an integer; see Process.setrlimit
.
Example:
Process.getrlimit(:CORE) # => [0, 18446744073709551615]
See Process.setrlimit
.
Not available on all platforms.