├── .gitmodules ├── LICENSE ├── README.md └── cmd ├── timescaledb-benchmark-delete └── main.go └── timescaledb-benchmark-query └── main.go /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "cmd/timescaledb-parallel-copy"] 2 | path = cmd/timescaledb-parallel-copy 3 | url = https://github.com/timescale/timescaledb-parallel-copy 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TimescaleDB vs PostgreSQL Benchmark 2 | 3 | ## Introduction 4 | This repository contains a collection of Go programs that can be used to 5 | benchmark [TimescaleDB][timescaledb] against PostgreSQL on insert, 6 | query, and deletion (data retention) performance. Additionally, we 7 | provide a [data set and queries][dataset] to allow you to measure 8 | performance [on the same data we have measured][blog]. 9 | 10 | ## Getting Started 11 | You will need the Go runtime (1.6+) installed on the machine 12 | you wish to benchmark. You can access this repo via `go get`: 13 | ```bash 14 | go get github.com/timescale/benchmark-postgres 15 | ``` 16 | 17 | There are three programs available for installation under the `cmd` 18 | directory, each of which can be installed with `go install`: 19 | ```bash 20 | # Change to program directory 21 | cd $GOPATH/src/github.com/timescale/benchmark-postgres/cmd/timescaledb-benchmark-query 22 | go get . 23 | go install 24 | 25 | # Repeat for other programs 26 | ``` 27 | 28 | ## Our Dataset 29 | 30 | In a [discussion of how TimescaleDB compares to PostgreSQL][blog], we 31 | used two datasets: one with 100M rows of CPU metrics and one with 1B 32 | rows. We have made the [100M row dataset available][dataset] 33 | (link will download 7GB archive) and use 34 | it throughout this README as an example. 35 | In addition to the data in CSV format, the archive 36 | also contains a file to create the table schema we used and a selection 37 | of queries we tested. 38 | 39 | The rows represent CPU metrics for 4000 hosts over the course of 3 days, 40 | `2016-01-01` through `2016-01-03`. Each row consists of a timestamp, a 41 | host identifier, and 10 CPU metrics. All hosts have a row every 10 42 | seconds for the duration of the 3 days, leading to just over 100M rows 43 | of data. The CSV is **20 GB** and when imported the database 44 | is **~30GB**. 45 | 46 | To unpack the archive: 47 | ```bash 48 | tar -vxjf benchmark_postgres.tar.bz2 49 | ``` 50 | 51 | This will unpack the following files into your current directory: 52 | 53 | * `cpu-data.csv` 54 | * `benchmark-setup-timescaledb.sql` 55 | * `benchmark-setup-postgresql.sql` 56 | * `queries-1-host-12-hr.sql` 57 | * `queries-8-host-1-hr.sql` 58 | * `queries-groupby-orderby-limit.sql` 59 | * `queries-groupby.sql` 60 | 61 | ## Usage 62 | 63 | ### Benchmark: Inserts (timescaledb-parallel-copy) 64 | In the `cmd` folder is a Git submodule to our [parallel copy][] program 65 | that is generally available. This program can actually double as a way 66 | to benchmark insert performance in either TimescaleDB or PostgreSQL. 67 | Make sure it is installed (see above) and you are ready to go. 68 | 69 | Using our 100M dataset, first you need to setup the database and tables. 70 | Create a database in PostgreSQL called, e.g., `benchmark`. Then, setup 71 | the tables using our provided schema: 72 | ```bash 73 | # To setup a TimescaleDB hypertable 74 | psql -d benchmark < benchmark-setup-timescaledb.sql 75 | # To setup a plain PostgreSQL table 76 | psql -d benchmark < benchmark-setup-postgresql.sql 77 | ``` 78 | 79 | Note that you can setup both tables in the same database for easy 80 | comparisons. To measure insert performance, run 81 | `timescaledb-parallel-copy` with the `--verbose` flag, and optionally 82 | a `--reporting-period` to get in-progress results: 83 | ```bash 84 | # For TimescaleDB, report every 30s 85 | timescaledb-parallel-copy --db-name=benchmark --table=cpu_ts \ 86 | --verbose --reporting-period=30s --file=cpu-data.csv 87 | 88 | # For PostgreSQL, report every 30s 89 | timescaledb-parallel-copy --db-name=benchmark --table=cpu_pg \ 90 | --verbose --reporting-period=30s --file=cpu-data.csv 91 | ``` 92 | 93 | Once the copy is finished, you'll be given an average number of rows 94 | per second over the whole insertion process. If you included a 95 | `--reporting-period` you can also see how the performance changes over 96 | time. 97 | 98 | ```bash 99 | at 20s, row rate 137950.621224/sec (period), row rate 137950.621224/sec (overall), 2.760000E+06 total rows 100 | at 40s, row rate 106634.481501/sec (period), row rate 122305.233000/sec (overall), 4.890000E+06 total rows 101 | ... 102 | at 14m40s, row rate 97544.843755/sec (period), row rate 112289.740923/sec (overall), 9.877000E+07 total rows 103 | at 15m0s, row rate 134560.614457/sec (period), row rate 112784.651475/sec (overall), 1.014600E+08 total rows 104 | COPY 103680000, took 15m18.895179s with 8 worker(s) (mean rate 112831.150209/sec) 105 | ``` 106 | 107 | ### Benchmark: Queries (timescaledb-benchmark-query) 108 | 109 | To benchmark query latency, we provide `timescaledb-benchmark-query`, 110 | which takes a file of queries (one per each line) and runs them in 111 | parallel. Each query is run twice, to generate 'cold' and 'warm' 112 | measurements for each, and the averages of both are printed after 113 | all the queries are run: 114 | ```bash 115 | timescaledb-benchmark-query --db-name=benchmark --table=cpu_ts \ 116 | --query-file=queries-1-host-12-hr.sql --workers=1 117 | 118 | avg of 'cold' 10 queries (ms): 19.90 119 | avg of 'warm' 10 queries (ms): 14.50 120 | ``` 121 | 122 | You can compare these numbers to PostgreSQL by changing the `--table` 123 | flag to point to a plain PostgreSQL table. 124 | 125 | Included in our 100M row dataset are queries of 4 types: 126 | 127 | * `1-host-12-hr`: Returns the max CPU usage per minute for 12 hours on one host 128 | * `8-host-1-hr`: Same as above except for 8 eights over 1 hour 129 | * `groupby`: Returns the avg CPU usage per host per hour over 24 hours 130 | * `groupby-orderby-limit`: Returns the last 5 max CPU usage per minute across all devices with a random time range end point 131 | 132 | _Note: The queries are missing the table name (replaced with %s), which 133 | is filled in later by the `--table` flag to `timescaledb-benchmark-query`._ 134 | 135 | ### Benchmark: Data Retention (timescaledb-benchmark-delete) 136 | 137 | Our final benchmark deals with measuring the cost of removing data after 138 | it falls outside of a retention period. TimescaleDB introduces a 139 | function called `drop_chunks()` to easily remove data older than a 140 | certain date. Combined with the way TimescaleDB organizes and stores 141 | data, this is much more efficient for removing data. 142 | 143 | To measure this, we provide `timescaledb-benchmark-delete` which can be 144 | used to delete data using `drop_chunks()` or SQL's `DELETE` command. 145 | Note that this program **does actually delete the data**, so if you 146 | using it, make sure the data loss is okay (i.e. **DO NOT USE** on 147 | production data). 148 | 149 | The program requires a start date from which to delete data, an amount 150 | to delete -- which should be equal to a chunk size for TimescaleDB, 151 | and the number of times to delete that amount of data. Our 100M row 152 | dataset begins on `2016-01-01` at midnight, so that is the start date 153 | we'll use along with 12-hour chunks. So, to delete the first 3 chunks 154 | we run: 155 | ```bash 156 | timescaledb-benchmark-delete --db-name=benchmark --table=cpu_ts \ 157 | --start="2016-01-01T00:00:00Z" --amount="12h" --limit=3 158 | ``` 159 | This will print out the command used and time it took to execute in 160 | milliseconds: 161 | ```bash 162 | SELECT drop_chunks('2016-01-01T12:00:00Z'::TIMESTAMPTZ, 'cpu_ts') 163 | 66ms 164 | 165 | SELECT drop_chunks('2016-01-02T00:00:00Z'::TIMESTAMPTZ, 'cpu_ts') 166 | 19ms 167 | 168 | SELECT drop_chunks('2016-01-02T12:00:00Z'::TIMESTAMPTZ, 'cpu_ts') 169 | 19ms 170 | ``` 171 | To benchmark the equivalent scenario on PostgreSQL requires you to 172 | disable the use of `drop_chunks()`: 173 | ```bash 174 | timescaledb-benchmark-delete --db-name=benchmark --table=cpu_pg \ 175 | --start="2016-01-01T00:00:00Z" --amount="12h" --limit=3 \ 176 | --use-drop-chunks=false 177 | ``` 178 | 179 | [timescaledb]: https://github.com/timescale/timescaledb 180 | [dataset]: https://timescaledata.blob.core.windows.net/datasets/benchmark_postgres.tar.bz2 181 | [blog]: https://blog.timescale.com/timescaledb-vs-6a696248104e 182 | [parallel copy]: https://github.com/timescale/timescaledb-parallel-copy 183 | -------------------------------------------------------------------------------- /cmd/timescaledb-benchmark-delete/main.go: -------------------------------------------------------------------------------- 1 | // timescaledb-benchmark-delete measures the time (in milliseconds) to delete data from two systems: 2 | // (1) TimescaleDB (by using the default --use-drop-chunks flag) 3 | // (2) PostgreSQL (by setting the --use-drop-chunks flag to 'false') 4 | // 5 | // Typical use for testing TimescaleDB 6 | // timescaledb-benchmark-delete --amount=6h --limit=5 7 | // 8 | // This will drop five 6-hour intervals from default database & table starting 9 | // at the default start date, outputting the SQL command used and the time 10 | // in milliseconds it took. By default, this uses TimescaleDB's `drop_chunks()` 11 | // function. 12 | // 13 | // ---------- 14 | // Typical use for testing PostgreSQL 15 | // timescaledb-benchmark-delete --amount=6h --limit=5 --use-drop-chunks=false 16 | // 17 | // This will drop five 6-hour intervals from default database & table starting 18 | // at the default start date, outputting the SQL command used and the time 19 | // in milliseconds it took. This will use a normal SQL `DELETE` command 20 | // 21 | package main 22 | 23 | import ( 24 | "flag" 25 | "fmt" 26 | "time" 27 | 28 | "github.com/jmoiron/sqlx" 29 | _ "github.com/lib/pq" 30 | ) 31 | 32 | // Program flag vars 33 | var ( 34 | postgresConnect string 35 | databaseName string 36 | table string 37 | 38 | dropChunks bool 39 | startDate string 40 | amount time.Duration 41 | limit uint 42 | ) 43 | 44 | const goTimeFmt = "2006-01-02T15:04:05Z" 45 | 46 | // Parse flags 47 | func init() { 48 | flag.StringVar(&postgresConnect, "postgres", "host=localhost user=postgres sslmode=disable", "Postgres connection url") 49 | flag.StringVar(&databaseName, "db-name", "benchmark", "Name of database to connect to") 50 | flag.StringVar(&table, "table", "test", "Table to remove data from") 51 | 52 | flag.BoolVar(&dropChunks, "use-drop-chunks", true, "Whether to use TimescaleDB function drop_chunks(). Set to false to test PostgreSQL") 53 | flag.StringVar(&startDate, "start", "2016-01-01T00:00:00Z", "Start date to delete from using the form YYYY-MM-DDThh:mm:ssZ") 54 | flag.DurationVar(&amount, "amount", 1*time.Hour, "Amount of data to delete given as a duration of time (e.g. 3h = 3 hours worth)") 55 | flag.UintVar(&limit, "limit", 1, "Number of times to delete --amount of data starting from --start") 56 | 57 | flag.Parse() 58 | } 59 | 60 | func getConnectString() string { 61 | return postgresConnect + " dbname=" + databaseName 62 | } 63 | 64 | func getDeleteQuery(t time.Time) string { 65 | if dropChunks { 66 | return fmt.Sprintf("SELECT drop_chunks('%s'::TIMESTAMPTZ, '%s')", t.Add(amount).Format(goTimeFmt), table) 67 | } 68 | end := t.Add(amount) 69 | return fmt.Sprintf("DELETE FROM \"%s\" WHERE time >= '%v' AND time < '%v'", table, t.Format(goTimeFmt), end.Format(goTimeFmt)) 70 | } 71 | 72 | func main() { 73 | db := sqlx.MustConnect("postgres", getConnectString()) 74 | defer db.Close() 75 | 76 | // Parse starting date for delete queries 77 | rangeStart, err := time.Parse(goTimeFmt, startDate) 78 | if err != nil { 79 | panic(fmt.Sprintf("could not parse start date: %v\n", err)) 80 | } 81 | 82 | // Delete data sized by --amount (in terms of time) and for --limit iterations 83 | for i := uint(0); i < limit; i++ { 84 | start := time.Now() 85 | q := getDeleteQuery(rangeStart) 86 | rows, err := db.Queryx(q) 87 | if err != nil { 88 | panic(err) 89 | } 90 | rows.Close() 91 | 92 | // Calculate and print elapsed time 93 | took := time.Now().Sub(start) 94 | fmt.Printf("%s\n%vms\n\n", q, took.Nanoseconds()/1e6) 95 | 96 | // Update starting time for potential next iteration 97 | rangeStart = rangeStart.Add(amount) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /cmd/timescaledb-benchmark-query/main.go: -------------------------------------------------------------------------------- 1 | // timescaledb-benchmark-query measures the time (in milliseconds) to run SQL queries on a PostgreSQL 2 | // based-system, for example: 3 | // (1) TimescaleDB 4 | // (2) PostgreSQL 5 | // 6 | // As input, it takes a file with a query on each line to run, and runs them twice 7 | // back-to-back to get 'cold' and 'warm' latency numbers. These queries should be 8 | // of similar construction for the most useful numbers. That is, given a query type 9 | // it should need roughly the same number of rows to answer. For example, asking for 10 | // the average of a metric per minute over an hour and varying which hour to query 11 | // is a better query construction than asking for the average of a metric per minute 12 | // over a variable time period. 13 | // 14 | // Typical use for testing 15 | // timescaledb-benchmark-delete --query-file=foo.sql 16 | // 17 | // This will run all the queries in foo.sql on the default database and table. 18 | // You can change the database with --db-name or the table with --table to try 19 | // it on non-TimescaleDB databases/tables vs TimescaleDB databases/tables. 20 | // 21 | package main 22 | 23 | import ( 24 | "bufio" 25 | "flag" 26 | "fmt" 27 | "log" 28 | "os" 29 | "sync" 30 | "sync/atomic" 31 | "time" 32 | 33 | "github.com/jmoiron/sqlx" 34 | _ "github.com/lib/pq" 35 | ) 36 | 37 | // Program flag vars 38 | var ( 39 | postgresConnect string 40 | databaseName string 41 | table string 42 | 43 | queryFile string 44 | workers uint64 45 | ) 46 | 47 | var ( 48 | queryChan chan string 49 | workersGroup sync.WaitGroup 50 | 51 | cold int64 52 | warm int64 53 | cnt int64 54 | ) 55 | 56 | // Parse flags 57 | func init() { 58 | flag.StringVar(&postgresConnect, "postgres", "host=localhost user=postgres sslmode=disable", "Postgres connection url") 59 | flag.StringVar(&databaseName, "db-name", "benchmark", "Name of database to connect to") 60 | flag.StringVar(&table, "table", "test", "Table to remove data from") 61 | 62 | flag.StringVar(&queryFile, "query-file", "", "Path to file containing queries to execute") 63 | flag.Uint64Var(&workers, "workers", 1, "Number of parallel queries to run") 64 | flag.Parse() 65 | } 66 | 67 | func getConnectString() string { 68 | return postgresConnect + " dbname=" + databaseName 69 | } 70 | 71 | func main() { 72 | if len(queryFile) <= 0 { 73 | fmt.Println("ERROR: --query-file not specified") 74 | os.Exit(1) 75 | } 76 | var scanner *bufio.Scanner 77 | file, err := os.Open(queryFile) 78 | if err != nil { 79 | log.Fatal(err) 80 | } 81 | defer file.Close() 82 | queryChan = make(chan string, workers) 83 | 84 | scanner = bufio.NewScanner(file) 85 | rows := make([]string, 0) 86 | for scanner.Scan() { 87 | rows = append(rows, scanner.Text()) 88 | } 89 | 90 | if err := scanner.Err(); err != nil { 91 | log.Fatalf("Error reading input: %s", err.Error()) 92 | } 93 | 94 | for i := uint64(0); i < workers; i++ { 95 | workersGroup.Add(1) 96 | go processQueries() 97 | } 98 | 99 | for _, r := range rows { 100 | queryChan <- r 101 | } 102 | close(queryChan) 103 | workersGroup.Wait() 104 | 105 | fmt.Printf("avg of 'cold' %d queries (ms): %8.2f\n", cnt, float64(cold)/float64(cnt)) 106 | fmt.Printf("avg of 'warm' %d queries (ms): %8.2f\n", cnt, float64(warm)/float64(cnt)) 107 | } 108 | 109 | func processQueries() { 110 | db := sqlx.MustConnect("postgres", getConnectString()) 111 | defer db.Close() 112 | 113 | sumCold := int64(0) 114 | sumWarm := int64(0) 115 | count := int64(0) 116 | for qFmt := range queryChan { 117 | q := fmt.Sprintf(qFmt, table) 118 | start := time.Now() 119 | res, err := db.Queryx(q) 120 | if err != nil { 121 | panic(err) 122 | } 123 | res.Close() 124 | took := time.Now().Sub(start) 125 | sumCold += took.Nanoseconds() / 1e6 126 | 127 | start = time.Now() 128 | res, err = db.Queryx(q) 129 | if err != nil { 130 | panic(err) 131 | } 132 | res.Close() 133 | took = time.Now().Sub(start) 134 | sumWarm += took.Nanoseconds() / 1e6 135 | 136 | count++ 137 | } 138 | 139 | atomic.AddInt64(&cold, sumCold) 140 | atomic.AddInt64(&warm, sumWarm) 141 | atomic.AddInt64(&cnt, count) 142 | workersGroup.Done() 143 | } 144 | --------------------------------------------------------------------------------