1PGBENCH(1)               PostgreSQL 12.2 Documentation              PGBENCH(1)
2
3
4

NAME

6       pgbench - run a benchmark test on PostgreSQL
7

SYNOPSIS

9       pgbench -i [option...] [dbname]
10
11       pgbench [option...] [dbname]
12

DESCRIPTION

14       pgbench is a simple program for running benchmark tests on PostgreSQL.
15       It runs the same sequence of SQL commands over and over, possibly in
16       multiple concurrent database sessions, and then calculates the average
17       transaction rate (transactions per second). By default, pgbench tests a
18       scenario that is loosely based on TPC-B, involving five SELECT, UPDATE,
19       and INSERT commands per transaction. However, it is easy to test other
20       cases by writing your own transaction script files.
21
22       Typical output from pgbench looks like:
23
24           transaction type: <builtin: TPC-B (sort of)>
25           scaling factor: 10
26           query mode: simple
27           number of clients: 10
28           number of threads: 1
29           number of transactions per client: 1000
30           number of transactions actually processed: 10000/10000
31           tps = 85.184871 (including connections establishing)
32           tps = 85.296346 (excluding connections establishing)
33
34       The first six lines report some of the most important parameter
35       settings. The next line reports the number of transactions completed
36       and intended (the latter being just the product of number of clients
37       and number of transactions per client); these will be equal unless the
38       run failed before completion. (In -T mode, only the actual number of
39       transactions is printed.) The last two lines report the number of
40       transactions per second, figured with and without counting the time to
41       start database sessions.
42
43       The default TPC-B-like transaction test requires specific tables to be
44       set up beforehand.  pgbench should be invoked with the -i (initialize)
45       option to create and populate these tables. (When you are testing a
46       custom script, you don't need this step, but will instead need to do
47       whatever setup your test needs.) Initialization looks like:
48
49           pgbench -i [ other-options ] dbname
50
51       where dbname is the name of the already-created database to test in.
52       (You may also need -h, -p, and/or -U options to specify how to connect
53       to the database server.)
54
55           Caution
56           pgbench -i creates four tables pgbench_accounts, pgbench_branches,
57           pgbench_history, and pgbench_tellers, destroying any existing
58           tables of these names. Be very careful to use another database if
59           you have tables having these names!
60
61       At the default “scale factor” of 1, the tables initially contain this
62       many rows:
63
64           table                   # of rows
65           ---------------------------------
66           pgbench_branches        1
67           pgbench_tellers         10
68           pgbench_accounts        100000
69           pgbench_history         0
70
71       You can (and, for most purposes, probably should) increase the number
72       of rows by using the -s (scale factor) option. The -F (fillfactor)
73       option might also be used at this point.
74
75       Once you have done the necessary setup, you can run your benchmark with
76       a command that doesn't include -i, that is
77
78           pgbench [ options ] dbname
79
80       In nearly all cases, you'll need some options to make a useful test.
81       The most important options are -c (number of clients), -t (number of
82       transactions), -T (time limit), and -f (specify a custom script file).
83       See below for a full list.
84

OPTIONS

86       The following is divided into three subsections. Different options are
87       used during database initialization and while running benchmarks, but
88       some options are useful in both cases.
89
90   Initialization Options
91       pgbench accepts the following command-line initialization arguments:
92
93       -i
94       --initialize
95           Required to invoke initialization mode.
96
97       -I init_steps
98       --init-steps=init_steps
99           Perform just a selected set of the normal initialization steps.
100           init_steps specifies the initialization steps to be performed,
101           using one character per step. Each step is invoked in the specified
102           order. The default is dtgvp. The available steps are:
103
104           d (Drop)
105               Drop any existing pgbench tables.
106
107           t (create Tables)
108               Create the tables used by the standard pgbench scenario, namely
109               pgbench_accounts, pgbench_branches, pgbench_history, and
110               pgbench_tellers.
111
112           g (Generate data)
113               Generate data and load it into the standard tables, replacing
114               any data already present.
115
116           v (Vacuum)
117               Invoke VACUUM on the standard tables.
118
119           p (create Primary keys)
120               Create primary key indexes on the standard tables.
121
122           f (create Foreign keys)
123               Create foreign key constraints between the standard tables.
124               (Note that this step is not performed by default.)
125
126
127       -F fillfactor
128       --fillfactor=fillfactor
129           Create the pgbench_accounts, pgbench_tellers and pgbench_branches
130           tables with the given fillfactor. Default is 100.
131
132       -n
133       --no-vacuum
134           Perform no vacuuming during initialization. (This option suppresses
135           the v initialization step, even if it was specified in -I.)
136
137       -q
138       --quiet
139           Switch logging to quiet mode, producing only one progress message
140           per 5 seconds. The default logging prints one message each 100000
141           rows, which often outputs many lines per second (especially on good
142           hardware).
143
144       -s scale_factor
145       --scale=scale_factor
146           Multiply the number of rows generated by the scale factor. For
147           example, -s 100 will create 10,000,000 rows in the pgbench_accounts
148           table. Default is 1. When the scale is 20,000 or larger, the
149           columns used to hold account identifiers (aid columns) will switch
150           to using larger integers (bigint), in order to be big enough to
151           hold the range of account identifiers.
152
153       --foreign-keys
154           Create foreign key constraints between the standard tables. (This
155           option adds the f step to the initialization step sequence, if it
156           is not already present.)
157
158       --index-tablespace=index_tablespace
159           Create indexes in the specified tablespace, rather than the default
160           tablespace.
161
162       --tablespace=tablespace
163           Create tables in the specified tablespace, rather than the default
164           tablespace.
165
166       --unlogged-tables
167           Create all tables as unlogged tables, rather than permanent tables.
168
169   Benchmarking Options
170       pgbench accepts the following command-line benchmarking arguments:
171
172       -b scriptname[@weight]
173       --builtin=scriptname[@weight]
174           Add the specified built-in script to the list of executed scripts.
175           An optional integer weight after @ allows to adjust the probability
176           of drawing the script. If not specified, it is set to 1. Available
177           built-in scripts are: tpcb-like, simple-update and select-only.
178           Unambiguous prefixes of built-in names are accepted. With special
179           name list, show the list of built-in scripts and exit immediately.
180
181       -c clients
182       --client=clients
183           Number of clients simulated, that is, number of concurrent database
184           sessions. Default is 1.
185
186       -C
187       --connect
188           Establish a new connection for each transaction, rather than doing
189           it just once per client session. This is useful to measure the
190           connection overhead.
191
192       -d
193       --debug
194           Print debugging output.
195
196       -D varname=value
197       --define=varname=value
198           Define a variable for use by a custom script (see below). Multiple
199           -D options are allowed.
200
201       -f filename[@weight]
202       --file=filename[@weight]
203           Add a transaction script read from filename to the list of executed
204           scripts. An optional integer weight after @ allows to adjust the
205           probability of drawing the test. See below for details.
206
207       -j threads
208       --jobs=threads
209           Number of worker threads within pgbench. Using more than one thread
210           can be helpful on multi-CPU machines. Clients are distributed as
211           evenly as possible among available threads. Default is 1.
212
213       -l
214       --log
215           Write information about each transaction to a log file. See below
216           for details.
217
218       -L limit
219       --latency-limit=limit
220           Transactions that last more than limit milliseconds are counted and
221           reported separately, as late.
222
223           When throttling is used (--rate=...), transactions that lag behind
224           schedule by more than limit ms, and thus have no hope of meeting
225           the latency limit, are not sent to the server at all. They are
226           counted and reported separately as skipped.
227
228       -M querymode
229       --protocol=querymode
230           Protocol to use for submitting queries to the server:
231
232           ·   simple: use simple query protocol.
233
234           ·   extended: use extended query protocol.
235
236           ·   prepared: use extended query protocol with prepared statements.
237
238           In the prepared mode, pgbench reuses the parse analysis result
239           starting from the second query iteration, so pgbench runs faster
240           than in other modes.
241
242           The default is simple query protocol. (See Chapter 52 for more
243           information.)
244
245       -n
246       --no-vacuum
247           Perform no vacuuming before running the test. This option is
248           necessary if you are running a custom test scenario that does not
249           include the standard tables pgbench_accounts, pgbench_branches,
250           pgbench_history, and pgbench_tellers.
251
252       -N
253       --skip-some-updates
254           Run built-in simple-update script. Shorthand for -b simple-update.
255
256       -P sec
257       --progress=sec
258           Show progress report every sec seconds. The report includes the
259           time since the beginning of the run, the TPS since the last report,
260           and the transaction latency average and standard deviation since
261           the last report. Under throttling (-R), the latency is computed
262           with respect to the transaction scheduled start time, not the
263           actual transaction beginning time, thus it also includes the
264           average schedule lag time.
265
266       -r
267       --report-latencies
268           Report the average per-statement latency (execution time from the
269           perspective of the client) of each command after the benchmark
270           finishes. See below for details.
271
272       -R rate
273       --rate=rate
274           Execute transactions targeting the specified rate instead of
275           running as fast as possible (the default). The rate is given in
276           transactions per second. If the targeted rate is above the maximum
277           possible rate, the rate limit won't impact the results.
278
279           The rate is targeted by starting transactions along a
280           Poisson-distributed schedule time line. The expected start time
281           schedule moves forward based on when the client first started, not
282           when the previous transaction ended. That approach means that when
283           transactions go past their original scheduled end time, it is
284           possible for later ones to catch up again.
285
286           When throttling is active, the transaction latency reported at the
287           end of the run is calculated from the scheduled start times, so it
288           includes the time each transaction had to wait for the previous
289           transaction to finish. The wait time is called the schedule lag
290           time, and its average and maximum are also reported separately. The
291           transaction latency with respect to the actual transaction start
292           time, i.e. the time spent executing the transaction in the
293           database, can be computed by subtracting the schedule lag time from
294           the reported latency.
295
296           If --latency-limit is used together with --rate, a transaction can
297           lag behind so much that it is already over the latency limit when
298           the previous transaction ends, because the latency is calculated
299           from the scheduled start time. Such transactions are not sent to
300           the server, but are skipped altogether and counted separately.
301
302           A high schedule lag time is an indication that the system cannot
303           process transactions at the specified rate, with the chosen number
304           of clients and threads. When the average transaction execution time
305           is longer than the scheduled interval between each transaction,
306           each successive transaction will fall further behind, and the
307           schedule lag time will keep increasing the longer the test run is.
308           When that happens, you will have to reduce the specified
309           transaction rate.
310
311       -s scale_factor
312       --scale=scale_factor
313           Report the specified scale factor in pgbench's output. With the
314           built-in tests, this is not necessary; the correct scale factor
315           will be detected by counting the number of rows in the
316           pgbench_branches table. However, when testing only custom
317           benchmarks (-f option), the scale factor will be reported as 1
318           unless this option is used.
319
320       -S
321       --select-only
322           Run built-in select-only script. Shorthand for -b select-only.
323
324       -t transactions
325       --transactions=transactions
326           Number of transactions each client runs. Default is 10.
327
328       -T seconds
329       --time=seconds
330           Run the test for this many seconds, rather than a fixed number of
331           transactions per client.  -t and -T are mutually exclusive.
332
333       -v
334       --vacuum-all
335           Vacuum all four standard tables before running the test. With
336           neither -n nor -v, pgbench will vacuum the pgbench_tellers and
337           pgbench_branches tables, and will truncate pgbench_history.
338
339       --aggregate-interval=seconds
340           Length of aggregation interval (in seconds). May be used only with
341           -l option. With this option, the log contains per-interval summary
342           data, as described below.
343
344       --log-prefix=prefix
345           Set the filename prefix for the log files created by --log. The
346           default is pgbench_log.
347
348       --progress-timestamp
349           When showing progress (option -P), use a timestamp (Unix epoch)
350           instead of the number of seconds since the beginning of the run.
351           The unit is in seconds, with millisecond precision after the dot.
352           This helps compare logs generated by various tools.
353
354       --random-seed=SEED
355           Set random generator seed. Seeds the system random number
356           generator, which then produces a sequence of initial generator
357           states, one for each thread. Values for SEED may be: time (the
358           default, the seed is based on the current time), rand (use a strong
359           random source, failing if none is available), or an unsigned
360           decimal integer value. The random generator is invoked explicitly
361           from a pgbench script (random...  functions) or implicitly (for
362           instance option --rate uses it to schedule transactions). When
363           explicitly set, the value used for seeding is shown on the
364           terminal. Any value allowed for SEED may also be provided through
365           the environment variable PGBENCH_RANDOM_SEED. To ensure that the
366           provided seed impacts all possible uses, put this option first or
367           use the environment variable.
368
369           Setting the seed explicitly allows to reproduce a pgbench run
370           exactly, as far as random numbers are concerned. As the random
371           state is managed per thread, this means the exact same pgbench run
372           for an identical invocation if there is one client per thread and
373           there are no external or data dependencies. From a statistical
374           viewpoint reproducing runs exactly is a bad idea because it can
375           hide the performance variability or improve performance unduly,
376           e.g. by hitting the same pages as a previous run. However, it may
377           also be of great help for debugging, for instance re-running a
378           tricky case which leads to an error. Use wisely.
379
380       --sampling-rate=rate
381           Sampling rate, used when writing data into the log, to reduce the
382           amount of log generated. If this option is given, only the
383           specified fraction of transactions are logged. 1.0 means all
384           transactions will be logged, 0.05 means only 5% of the transactions
385           will be logged.
386
387           Remember to take the sampling rate into account when processing the
388           log file. For example, when computing TPS values, you need to
389           multiply the numbers accordingly (e.g. with 0.01 sample rate,
390           you'll only get 1/100 of the actual TPS).
391
392   Common Options
393       pgbench accepts the following command-line common arguments:
394
395       -h hostname
396       --host=hostname
397           The database server's host name
398
399       -p port
400       --port=port
401           The database server's port number
402
403       -U login
404       --username=login
405           The user name to connect as
406
407       -V
408       --version
409           Print the pgbench version and exit.
410
411       -?
412       --help
413           Show help about pgbench command line arguments, and exit.
414

EXIT STATUS

416       A successful run will exit with status 0. Exit status 1 indicates
417       static problems such as invalid command-line options. Errors during the
418       run such as database errors or problems in the script will result in
419       exit status 2. In the latter case, pgbench will print partial results.
420

NOTES

422   What Is the “Transaction” Actually Performed in pgbench?
423       pgbench executes test scripts chosen randomly from a specified list.
424       They include built-in scripts with -b and user-provided custom scripts
425       with -f. Each script may be given a relative weight specified after a @
426       so as to change its drawing probability. The default weight is 1.
427       Scripts with a weight of 0 are ignored.
428
429       The default built-in transaction script (also invoked with -b
430       tpcb-like) issues seven commands per transaction over randomly chosen
431       aid, tid, bid and delta. The scenario is inspired by the TPC-B
432       benchmark, but is not actually TPC-B, hence the name.
433
434        1. BEGIN;
435
436        2. UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid
437           = :aid;
438
439        3. SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
440
441        4. UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid =
442           :tid;
443
444        5. UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid
445           = :bid;
446
447        6. INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES
448           (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
449
450        7. END;
451
452       If you select the simple-update built-in (also -N), steps 4 and 5
453       aren't included in the transaction. This will avoid update contention
454       on these tables, but it makes the test case even less like TPC-B.
455
456       If you select the select-only built-in (also -S), only the SELECT is
457       issued.
458
459   Custom Scripts
460       pgbench has support for running custom benchmark scenarios by replacing
461       the default transaction script (described above) with a transaction
462       script read from a file (-f option). In this case a “transaction”
463       counts as one execution of a script file.
464
465       A script file contains one or more SQL commands terminated by
466       semicolons. Empty lines and lines beginning with -- are ignored. Script
467       files can also contain “meta commands”, which are interpreted by
468       pgbench itself, as described below.
469
470           Note
471           Before PostgreSQL 9.6, SQL commands in script files were terminated
472           by newlines, and so they could not be continued across lines. Now a
473           semicolon is required to separate consecutive SQL commands (though
474           a SQL command does not need one if it is followed by a meta
475           command). If you need to create a script file that works with both
476           old and new versions of pgbench, be sure to write each SQL command
477           on a single line ending with a semicolon.
478
479       There is a simple variable-substitution facility for script files.
480       Variable names must consist of letters (including non-Latin letters),
481       digits, and underscores. Variables can be set by the command-line -D
482       option, explained above, or by the meta commands explained below. In
483       addition to any variables preset by -D command-line options, there are
484       a few variables that are preset automatically, listed in Table 257. A
485       value specified for these variables using -D takes precedence over the
486       automatic presets. Once set, a variable's value can be inserted into a
487       SQL command by writing :variablename. When running more than one client
488       session, each session has its own set of variables.  pgbench supports
489       up to 255 variable uses in one statement.
490
491       Table 257. Automatic Variables
492       ┌─────────────┬────────────────────────────┐
493Variable     Description                
494       ├─────────────┼────────────────────────────┤
495       │client_id    │ unique number identifying  │
496       │             │ the client session (starts │
497       │             │ from zero)                 │
498       ├─────────────┼────────────────────────────┤
499       │default_seed │ seed used in hash          │
500       │             │ functions by default       │
501       ├─────────────┼────────────────────────────┤
502       │random_seed  │ random generator seed      │
503       │             │ (unless overwritten with   │
504       │             │ -D)                        │
505       ├─────────────┼────────────────────────────┤
506       │scale        │ current scale factor       │
507       └─────────────┴────────────────────────────┘
508
509       Script file meta commands begin with a backslash (\) and normally
510       extend to the end of the line, although they can be continued to
511       additional lines by writing backslash-return. Arguments to a meta
512       command are separated by white space. These meta commands are
513       supported:
514
515       \gset [prefix]
516           This command may be used to end SQL queries, taking the place of
517           the terminating semicolon (;).
518
519           When this command is used, the preceding SQL query is expected to
520           return one row, the columns of which are stored into variables
521           named after column names, and prefixed with prefix if provided.
522
523           The following example puts the final account balance from the first
524           query into variable abalance, and fills variables p_two and p_three
525           with integers from the third query. The result of the second query
526           is discarded.
527
528               UPDATE pgbench_accounts
529                 SET abalance = abalance + :delta
530                 WHERE aid = :aid
531                 RETURNING abalance \gset
532               -- compound of two queries
533               SELECT 1 \;
534               SELECT 2 AS two, 3 AS three \gset p_
535
536
537       \if expression
538       \elif expression
539       \else
540       \endif
541           This group of commands implements nestable conditional blocks,
542           similarly to psql's \if expression. Conditional expressions are
543           identical to those with \set, with non-zero values interpreted as
544           true.
545
546       \set varname expression
547           Sets variable varname to a value calculated from expression. The
548           expression may contain the NULL constant, Boolean constants TRUE
549           and FALSE, integer constants such as 5432, double constants such as
550           3.14159, references to variables :variablename, operators with
551           their usual SQL precedence and associativity, function calls, SQL
552           CASE generic conditional expressions and parentheses.
553
554           Functions and most operators return NULL on NULL input.
555
556           For conditional purposes, non zero numerical values are TRUE, zero
557           numerical values and NULL are FALSE.
558
559           Too large or small integer and double constants, as well as integer
560           arithmetic operators (+, -, * and /) raise errors on overflows.
561
562           When no final ELSE clause is provided to a CASE, the default value
563           is NULL.
564
565           Examples:
566
567               \set ntellers 10 * :scale
568               \set aid (1021 * random(1, 100000 * :scale)) % \
569                          (100000 * :scale) + 1
570               \set divx CASE WHEN :x <> 0 THEN :y/:x ELSE NULL END
571
572       \sleep number [ us | ms | s ]
573           Causes script execution to sleep for the specified duration in
574           microseconds (us), milliseconds (ms) or seconds (s). If the unit is
575           omitted then seconds are the default.  number can be either an
576           integer constant or a :variablename reference to a variable having
577           an integer value.
578
579           Example:
580
581               \sleep 10 ms
582
583       \setshell varname command [ argument ... ]
584           Sets variable varname to the result of the shell command command
585           with the given argument(s). The command must return an integer
586           value through its standard output.
587
588           command and each argument can be either a text constant or a
589           :variablename reference to a variable. If you want to use an
590           argument starting with a colon, write an additional colon at the
591           beginning of argument.
592
593           Example:
594
595               \setshell variable_to_be_assigned command literal_argument :variable ::literal_starting_with_colon
596
597       \shell command [ argument ... ]
598           Same as \setshell, but the result of the command is discarded.
599
600           Example:
601
602               \shell command literal_argument :variable ::literal_starting_with_colon
603
604   Built-in Operators
605       The arithmetic, bitwise, comparison and logical operators listed in
606       Table 258 are built into pgbench and may be used in expressions
607       appearing in \set.
608
609       Table 258. pgbench Operators by Increasing Precedence
610       ┌──────────────────┬──────────────────┬───────────┬────────┐
611Operator          Description      Example   Result 
612       ├──────────────────┼──────────────────┼───────────┼────────┤
613       │OR                │ logical or       │ 5 or 0    │ TRUE   │
614       ├──────────────────┼──────────────────┼───────────┼────────┤
615       │AND               │ logical and      │ 3 and 0   │ FALSE  │
616       ├──────────────────┼──────────────────┼───────────┼────────┤
617       │NOT               │ logical not      │ not false │ TRUE   │
618       ├──────────────────┼──────────────────┼───────────┼────────┤
619       │IS [NOT]          │ value tests      │ 1 is null │ FALSE  │
620       │(NULL|TRUE|FALSE) │                  │           │        │
621       ├──────────────────┼──────────────────┼───────────┼────────┤
622       │ISNULL|NOTNULL    │ null tests       │ 1 notnull │ TRUE   │
623       ├──────────────────┼──────────────────┼───────────┼────────┤
624       │=                 │ is equal         │ 5 = 4     │ FALSE  │
625       ├──────────────────┼──────────────────┼───────────┼────────┤
626       │<>                │ is not equal     │ 5 <> 4    │ TRUE   │
627       ├──────────────────┼──────────────────┼───────────┼────────┤
628       │!=                │ is not equal     │ 5 != 5    │ FALSE  │
629       ├──────────────────┼──────────────────┼───────────┼────────┤
630       │<                 │ lower than       │ 5 < 4     │ FALSE  │
631       ├──────────────────┼──────────────────┼───────────┼────────┤
632       │<=                │ lower or equal   │ 5 <= 4    │ FALSE  │
633       ├──────────────────┼──────────────────┼───────────┼────────┤
634       │>                 │ greater than     │ 5 > 4     │ TRUE   │
635       ├──────────────────┼──────────────────┼───────────┼────────┤
636       │>=                │ greater or equal │ 5 >= 4    │ TRUE   │
637       ├──────────────────┼──────────────────┼───────────┼────────┤
638       │|                 │ integer bitwise  │ 1 | 2     │ 3      │
639       │                  │ OR               │           │        │
640       ├──────────────────┼──────────────────┼───────────┼────────┤
641       │#                 │ integer bitwise  │ 1 # 3     │ 2      │
642       │                  │ XOR              │           │        │
643       ├──────────────────┼──────────────────┼───────────┼────────┤
644       │&                 │ integer bitwise  │ 1 & 3     │ 1      │
645       │                  │ AND              │           │        │
646       ├──────────────────┼──────────────────┼───────────┼────────┤
647       │~                 │ integer bitwise  │ ~ 1       │ -2     │
648       │                  │ NOT              │           │        │
649       ├──────────────────┼──────────────────┼───────────┼────────┤
650       │<<                │ integer bitwise  │ 1 << 2    │ 4      │
651       │                  │ shift left       │           │        │
652       ├──────────────────┼──────────────────┼───────────┼────────┤
653       │>>                │ integer bitwise  │ 8 >> 2    │ 2      │
654       │                  │ shift right      │           │        │
655       ├──────────────────┼──────────────────┼───────────┼────────┤
656       │+                 │ addition         │ 5 + 4     │ 9      │
657       ├──────────────────┼──────────────────┼───────────┼────────┤
658       │-                 │ subtraction      │ 3 - 2.0   │ 1.0    │
659       ├──────────────────┼──────────────────┼───────────┼────────┤
660       │*                 │ multiplication   │ 5 * 4     │ 20     │
661       ├──────────────────┼──────────────────┼───────────┼────────┤
662       │/                 │ division         │ 5 / 3     │ 1      │
663       │                  │ (integer         │           │        │
664       │                  │ truncates the    │           │        │
665       │                  │ results)         │           │        │
666       ├──────────────────┼──────────────────┼───────────┼────────┤
667       │%                 │ modulo           │ 3 % 2     │ 1      │
668       ├──────────────────┼──────────────────┼───────────┼────────┤
669       │-                 │ opposite         │ - 2.0     │ -2.0   │
670       └──────────────────┴──────────────────┴───────────┴────────┘
671
672   Built-In Functions
673       The functions listed in Table 259 are built into pgbench and may be
674       used in expressions appearing in \set.
675
676       Table 259. pgbench Functions
677       ┌───────────────────────┬───────────────┬───────────────────────────┬───────────────────────┬────────────────────────┐
678Function               Return Type   Description               Example               Result                 
679       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
680abs(a)                 │ same as a     │ absolute                  │ abs(-17)              │ 17                     │
681       │                       │               │ value                     │                       │                        │
682       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
683debug(a)               │ same as a     │ print a to                │ debug(5432.1)         │ 5432.1                 │
684       │                       │               │ stderr,                   │                       │                        │
685       │                       │               │         and               │                       │                        │
686       │                       │               │ return a                  │                       │                        │
687       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
688double(i)              │ double        │ cast to                   │ double(5432)          │ 5432.0                 │
689       │                       │               │ double                    │                       │                        │
690       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
691exp(x)                 │ double        │ exponential               │ exp(1.0)              │ 2.718281828459045      │
692       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
693greatest(a [,          │ double if any │ largest value             │ greatest(5,           │ 5                      │
694... ] )                a is double,  │ among                     │ 4, 3, 2)              │                        │
695       │                       │ else integer  │ arguments                 │                       │                        │
696       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
697hash(a [,              │ integer       │ alias for                 │ hash(10,              │ -5817877081768721676   │
698seed ] )               │               │ hash_murmur2()            │ 5432)                 │                        │
699       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
700hash_fnv1a(a           │ integer       │ FNV-1a hash               │ hash_fnv1a(10,        │ -7793829335365542153   │
701[, seed ] )            │               │                           │ 5432)                 │                        │
702       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
703hash_murmur2(a         │ integer       │ MurmurHash2               │ hash_murmur2(10,      │ -5817877081768721676   │
704[, seed ] )            │               │ hash                      │ 5432)                 │                        │
705       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
706int(x)                 │ integer       │ cast to int               │ int(5.4 + 3.8)        │ 9                      │
707       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
708least(a [, ...         │ double if any │ smallest value            │ least(5, 4, 3,        │ 2.1                    │
709] )                    a is double,  │ among                     │ 2.1)                  │                        │
710       │                       │ else integer  │ arguments                 │                       │                        │
711       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
712ln(x)                  │ double        │ natural                   │ ln(2.718281828459045) │ 1.0                    │
713       │                       │               │ logarithm                 │                       │                        │
714       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
715mod(i, j)              │ integer       │ modulo                    │ mod(54, 32)           │ 22                     │
716       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
717pi()                   │ double        │ value of the              │ pi()                  │ 3.14159265358979323846 │
718       │                       │               │ constant PI               │                       │                        │
719       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
720pow(x, y),             │ double        │ exponentiation            │ pow(2.0, 10),         │ 1024.0                 │
721power(x, y)            │               │                           │ power(2.0, 10)        │                        │
722       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
723random(lb, ub)         │ integer       │ uniformly-distributed     │ random(1, 10)         │ an integer between 1   │
724       │                       │               │ random integer            │                       │ and 10                 │
725       │                       │               │ in [lb, ub]               │                       │                        │
726       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
727random_exponential(lb, │ integer       │ exponentially-distributed │ random_exponential(1, │ an integer between 1   │
728ub, parameter)         │               │ random integer in         │ 10, 3.0)              │ and 10                 │
729       │                       │               │ [lb, ub],                 │                       │                        │
730       │                       │               │               see         │                       │                        │
731       │                       │               │ below                     │                       │                        │
732       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
733random_gaussian(lb,    │ integer       │ Gaussian-distributed      │ random_gaussian(1,    │ an integer between 1   │
734ub, parameter)         │               │ random integer in [lb,    │ 10, 2.5)              │ and 10                 │
735       │                       │               │ ub],                      │                       │                        │
736       │                       │               │               see below   │                       │                        │
737       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
738random_zipfian(lb, ub, │ integer       │ Zipfian-distributed       │ random_zipfian(1, 10, │ an integer between 1   │
739parameter)             │               │ random integer in [lb,    │ 1.5)                  │ and 10                 │
740       │                       │               │ ub],                      │                       │                        │
741       │                       │               │               see below   │                       │                        │
742       ├───────────────────────┼───────────────┼───────────────────────────┼───────────────────────┼────────────────────────┤
743sqrt(x)                │ double        │ square root               │ sqrt(2.0)             │ 1.414213562            │
744       └───────────────────────┴───────────────┴───────────────────────────┴───────────────────────┴────────────────────────┘
745
746       The random function generates values using a uniform distribution, that
747       is all the values are drawn within the specified range with equal
748       probability. The random_exponential, random_gaussian and random_zipfian
749       functions require an additional double parameter which determines the
750       precise shape of the distribution.
751
752       ·   For an exponential distribution, parameter controls the
753           distribution by truncating a quickly-decreasing exponential
754           distribution at parameter, and then projecting onto integers
755           between the bounds. To be precise, with
756
757               f(x) = exp(-parameter * (x - min) / (max - min + 1)) / (1 - exp(-parameter))
758
759           Then value i between min and max inclusive is drawn with
760           probability: f(i) - f(i + 1).
761
762           Intuitively, the larger the parameter, the more frequently values
763           close to min are accessed, and the less frequently values close to
764           max are accessed. The closer to 0 parameter is, the flatter (more
765           uniform) the access distribution. A crude approximation of the
766           distribution is that the most frequent 1% values in the range,
767           close to min, are drawn parameter% of the time. The parameter value
768           must be strictly positive.
769
770       ·   For a Gaussian distribution, the interval is mapped onto a standard
771           normal distribution (the classical bell-shaped Gaussian curve)
772           truncated at -parameter on the left and +parameter on the right.
773           Values in the middle of the interval are more likely to be drawn.
774           To be precise, if PHI(x) is the cumulative distribution function of
775           the standard normal distribution, with mean mu defined as (max +
776           min) / 2.0, with
777
778               f(x) = PHI(2.0 * parameter * (x - mu) / (max - min + 1)) /
779                      (2.0 * PHI(parameter) - 1)
780
781           then value i between min and max inclusive is drawn with
782           probability: f(i + 0.5) - f(i - 0.5). Intuitively, the larger the
783           parameter, the more frequently values close to the middle of the
784           interval are drawn, and the less frequently values close to the min
785           and max bounds. About 67% of values are drawn from the middle 1.0 /
786           parameter, that is a relative 0.5 / parameter around the mean, and
787           95% in the middle 2.0 / parameter, that is a relative 1.0 /
788           parameter around the mean; for instance, if parameter is 4.0, 67%
789           of values are drawn from the middle quarter (1.0 / 4.0) of the
790           interval (i.e. from 3.0 / 8.0 to 5.0 / 8.0) and 95% from the middle
791           half (2.0 / 4.0) of the interval (second and third quartiles). The
792           minimum allowed parameter value is 2.0.
793
794       ·   random_zipfian generates a bounded Zipfian distribution.  parameter
795           defines how skewed the distribution is. The larger the parameter,
796           the more frequently values closer to the beginning of the interval
797           are drawn. The distribution is such that, assuming the range starts
798           from 1, the ratio of the probability of drawing k versus drawing
799           k+1 is ((k+1)/k)**parameter. For example, random_zipfian(1, ...,
800           2.5) produces the value 1 about (2/1)**2.5 = 5.66 times more
801           frequently than 2, which itself is produced (3/2)**2.5 = 2.76 times
802           more frequently than 3, and so on.
803
804           pgbench's implementation is based on "Non-Uniform Random Variate
805           Generation", Luc Devroye, p. 550-551, Springer 1986. Due to
806           limitations of that algorithm, the parameter value is restricted to
807           the range [1.001, 1000].
808
809       Hash functions hash, hash_murmur2 and hash_fnv1a accept an input value
810       and an optional seed parameter. In case the seed isn't provided the
811       value of :default_seed is used, which is initialized randomly unless
812       set by the command-line -D option. Hash functions can be used to
813       scatter the distribution of random functions such as random_zipfian or
814       random_exponential. For instance, the following pgbench script
815       simulates possible real world workload typical for social media and
816       blogging platforms where few accounts generate excessive load:
817
818           \set r random_zipfian(0, 100000000, 1.07)
819           \set k abs(hash(:r)) % 1000000
820
821       In some cases several distinct distributions are needed which don't
822       correlate with each other and this is when implicit seed parameter
823       comes in handy:
824
825           \set k1 abs(hash(:r, :default_seed + 123)) % 1000000
826           \set k2 abs(hash(:r, :default_seed + 321)) % 1000000
827
828       As an example, the full definition of the built-in TPC-B-like
829       transaction is:
830
831           \set aid random(1, 100000 * :scale)
832           \set bid random(1, 1 * :scale)
833           \set tid random(1, 10 * :scale)
834           \set delta random(-5000, 5000)
835           BEGIN;
836           UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
837           SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
838           UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
839           UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
840           INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
841           END;
842
843       This script allows each iteration of the transaction to reference
844       different, randomly-chosen rows. (This example also shows why it's
845       important for each client session to have its own variables — otherwise
846       they'd not be independently touching different rows.)
847
848   Per-Transaction Logging
849       With the -l option (but without the --aggregate-interval option),
850       pgbench writes information about each transaction to a log file. The
851       log file will be named prefix.nnn, where prefix defaults to
852       pgbench_log, and nnn is the PID of the pgbench process. The prefix can
853       be changed by using the --log-prefix option. If the -j option is 2 or
854       higher, so that there are multiple worker threads, each will have its
855       own log file. The first worker will use the same name for its log file
856       as in the standard single worker case. The additional log files for the
857       other workers will be named prefix.nnn.mmm, where mmm is a sequential
858       number for each worker starting with 1.
859
860       The format of the log is:
861
862           client_id transaction_no time script_no time_epoch time_us [ schedule_lag ]
863
864       where client_id indicates which client session ran the transaction,
865       transaction_no counts how many transactions have been run by that
866       session, time is the total elapsed transaction time in microseconds,
867       script_no identifies which script file was used (useful when multiple
868       scripts were specified with -f or -b), and time_epoch/time_us are a
869       Unix-epoch time stamp and an offset in microseconds (suitable for
870       creating an ISO 8601 time stamp with fractional seconds) showing when
871       the transaction completed. The schedule_lag field is the difference
872       between the transaction's scheduled start time, and the time it
873       actually started, in microseconds. It is only present when the --rate
874       option is used. When both --rate and --latency-limit are used, the time
875       for a skipped transaction will be reported as skipped.
876
877       Here is a snippet of a log file generated in a single-client run:
878
879           0 199 2241 0 1175850568 995598
880           0 200 2465 0 1175850568 998079
881           0 201 2513 0 1175850569 608
882           0 202 2038 0 1175850569 2663
883
884       Another example with --rate=100 and --latency-limit=5 (note the
885       additional schedule_lag column):
886
887           0 81 4621 0 1412881037 912698 3005
888           0 82 6173 0 1412881037 914578 4304
889           0 83 skipped 0 1412881037 914578 5217
890           0 83 skipped 0 1412881037 914578 5099
891           0 83 4722 0 1412881037 916203 3108
892           0 84 4142 0 1412881037 918023 2333
893           0 85 2465 0 1412881037 919759 740
894
895       In this example, transaction 82 was late, because its latency (6.173
896       ms) was over the 5 ms limit. The next two transactions were skipped,
897       because they were already late before they were even started.
898
899       When running a long test on hardware that can handle a lot of
900       transactions, the log files can become very large. The --sampling-rate
901       option can be used to log only a random sample of transactions.
902
903   Aggregated Logging
904       With the --aggregate-interval option, a different format is used for
905       the log files:
906
907           interval_start num_transactions sum_latency sum_latency_2 min_latency max_latency [ sum_lag sum_lag_2 min_lag max_lag [ skipped ] ]
908
909       where interval_start is the start of the interval (as a Unix epoch time
910       stamp), num_transactions is the number of transactions within the
911       interval, sum_latency is the sum of the transaction latencies within
912       the interval, sum_latency_2 is the sum of squares of the transaction
913       latencies within the interval, min_latency is the minimum latency
914       within the interval, and max_latency is the maximum latency within the
915       interval. The next fields, sum_lag, sum_lag_2, min_lag, and max_lag,
916       are only present if the --rate option is used. They provide statistics
917       about the time each transaction had to wait for the previous one to
918       finish, i.e. the difference between each transaction's scheduled start
919       time and the time it actually started. The very last field, skipped, is
920       only present if the --latency-limit option is used, too. It counts the
921       number of transactions skipped because they would have started too
922       late. Each transaction is counted in the interval when it was
923       committed.
924
925       Here is some example output:
926
927           1345828501 5601 1542744 483552416 61 2573
928           1345828503 7884 1979812 565806736 60 1479
929           1345828505 7208 1979422 567277552 59 1391
930           1345828507 7685 1980268 569784714 60 1398
931           1345828509 7073 1979779 573489941 236 1411
932
933       Notice that while the plain (unaggregated) log file shows which script
934       was used for each transaction, the aggregated log does not. Therefore
935       if you need per-script data, you need to aggregate the data on your
936       own.
937
938   Per-Statement Latencies
939       With the -r option, pgbench collects the elapsed transaction time of
940       each statement executed by every client. It then reports an average of
941       those values, referred to as the latency for each statement, after the
942       benchmark has finished.
943
944       For the default script, the output will look similar to this:
945
946           starting vacuum...end.
947           transaction type: <builtin: TPC-B (sort of)>
948           scaling factor: 1
949           query mode: simple
950           number of clients: 10
951           number of threads: 1
952           number of transactions per client: 1000
953           number of transactions actually processed: 10000/10000
954           latency average = 15.844 ms
955           latency stddev = 2.715 ms
956           tps = 618.764555 (including connections establishing)
957           tps = 622.977698 (excluding connections establishing)
958           statement latencies in milliseconds:
959                   0.002  \set aid random(1, 100000 * :scale)
960                   0.005  \set bid random(1, 1 * :scale)
961                   0.002  \set tid random(1, 10 * :scale)
962                   0.001  \set delta random(-5000, 5000)
963                   0.326  BEGIN;
964                   0.603  UPDATE pgbench_accounts SET abalance = abalance + :delta WHERE aid = :aid;
965                   0.454  SELECT abalance FROM pgbench_accounts WHERE aid = :aid;
966                   5.528  UPDATE pgbench_tellers SET tbalance = tbalance + :delta WHERE tid = :tid;
967                   7.335  UPDATE pgbench_branches SET bbalance = bbalance + :delta WHERE bid = :bid;
968                   0.371  INSERT INTO pgbench_history (tid, bid, aid, delta, mtime) VALUES (:tid, :bid, :aid, :delta, CURRENT_TIMESTAMP);
969                   1.212  END;
970
971       If multiple script files are specified, the averages are reported
972       separately for each script file.
973
974       Note that collecting the additional timing information needed for
975       per-statement latency computation adds some overhead. This will slow
976       average execution speed and lower the computed TPS. The amount of
977       slowdown varies significantly depending on platform and hardware.
978       Comparing average TPS values with and without latency reporting enabled
979       is a good way to measure if the timing overhead is significant.
980
981   Good Practices
982       It is very easy to use pgbench to produce completely meaningless
983       numbers. Here are some guidelines to help you get useful results.
984
985       In the first place, never believe any test that runs for only a few
986       seconds. Use the -t or -T option to make the run last at least a few
987       minutes, so as to average out noise. In some cases you could need hours
988       to get numbers that are reproducible. It's a good idea to try the test
989       run a few times, to find out if your numbers are reproducible or not.
990
991       For the default TPC-B-like test scenario, the initialization scale
992       factor (-s) should be at least as large as the largest number of
993       clients you intend to test (-c); else you'll mostly be measuring update
994       contention. There are only -s rows in the pgbench_branches table, and
995       every transaction wants to update one of them, so -c values in excess
996       of -s will undoubtedly result in lots of transactions blocked waiting
997       for other transactions.
998
999       The default test scenario is also quite sensitive to how long it's been
1000       since the tables were initialized: accumulation of dead rows and dead
1001       space in the tables changes the results. To understand the results you
1002       must keep track of the total number of updates and when vacuuming
1003       happens. If autovacuum is enabled it can result in unpredictable
1004       changes in measured performance.
1005
1006       A limitation of pgbench is that it can itself become the bottleneck
1007       when trying to test a large number of client sessions. This can be
1008       alleviated by running pgbench on a different machine from the database
1009       server, although low network latency will be essential. It might even
1010       be useful to run several pgbench instances concurrently, on several
1011       client machines, against the same database server.
1012
1013   Security
1014       If untrusted users have access to a database that has not adopted a
1015       secure schema usage pattern, do not run pgbench in that database.
1016       pgbench uses unqualified names and does not manipulate the search path.
1017
1018
1019
1020PostgreSQL 12.2                      2020                           PGBENCH(1)
Impressum