Giter VIP home page Giter VIP logo

1brc's Introduction

1BRC

1️⃣🐝🏎️ The One Billion Row Challenge -- A fun exploration of how quickly 1B rows from a text file can be aggregated. The challenge was primarily foces on Java but I decided to solve it in Golang!

I wrote a detailed blog about my implementation approach, you can check it out here.

Record of iterations

Final implementation approach looks like this:

final iteration visualised

Here is a more detailed record of each individual iteration:

Attempt Number Approach Execution Time Diff Commit
0 Naive Implementation: Read temperatures into a map of cities. Iterate serially over each key (city) in map to find min, max and average temperatures. 6:13.15
1 Evaluate each city in map concurrently using goroutines. 4:32.80 -100.35 8bd5f43
2 Remove sorting float64 slices. Calculate min, max and average by iterating. 4:25.59 -7.21 830e5df
3 Decouple reading and processing of file content. A buffered goroutine is used to communicate between the two processes. 5:22.83 +57.24 2babf7d
4 Instead of sending each line to the channel, now sending 100 lines chunked together. Also, to minimise garbage collection, not freeing up memory when resetting a slice. 3:41.76 -161.07 b7b1781
5 Read file in chunks of 100 MB instead of reading line by line. 3:32.62 -9.14 c26fea4
6 Convert temperature from string to int64, process in int64 and convert to float64 at the end. 2:51.50 -41.14 7812da4
7 In the city <> temperatures map, replaced the value for each key (city) to preprocessed min, max, count and sum of all temperatures instead of storing all recorded temperatures for the city. 1:39.81 -71.79 e5213a8
8 Use producer consumer pattern to read file in chunks and process the chunks in parallel. 1:43.82 +14.01 067f2a4
9 Reduce memory allocation by processing each read chunk into a map. Result channel now can collate the smaller processed chunk maps. 0:28.544 -75.286 d4153ac
10 Avoid string concatenation overhead by not reading the decimal point when processing city temperature. 0:24.571 -3.973 90f2fe1
11 Convert byte slice to string directly instead of using a strings.Builder. 0:18.910 -5.761 88bb6da
12 Replace strconv.ParseInt with a custom string to int parser. 0:14.008 -4.902 17d575f
13 Reduce map access calls when constructing final result string. 0:12.017 -1.9991

1brc's People

Contributors

shraddhaag avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

1brc's Issues

Speed up `processReadChunk` by alternating bytes.IndexByte calls

I would not be surprised if you could speed up https://github.com/shraddhaag/1brc/blob/8513d5e70a1bfabbf46ab86a9cb6558bc9805154/main.go#L187C6-L187C22 by alternating calling bytes.IndexByte(buf[lastTokenEnd:], ';'), followed by bytes.IndexByte(buf[lastTokenEnd:], '\n'). bytes.IndexByte function is highly optimized for fast searching in a byte slice. Since it is the inner loop it can have a big impact.

You could probably also skip the looking at the first 1 byte for station name and temperature (since it's at least one character). From my experience not inspecting bytes can be a very efficient way of speeding up parsing.

Also, I would convert from []byte to string only when I need to to avoid any kind of unicode handling.

unit tests are not passing go 1.22 amd

the unit tests didn't pass for me on go 1.22amd. They are all failing heres the first two:

--- FAIL: TestMain (0.22s)
    --- FAIL: TestMain/test_cases\measurements-1 (0.02s)
       billionlinechallenge\main_test.go:18: 
            	Error Trace:	billionlinechallenge/main_test.go:18
            	Error:      	Not equal: 
            	            	expected: "{Kunming=19.8/19.8/19.8}\r\n"
            	            	actual  : "{Kunming=0.0/0.0/0.0}\n"
            	            	
            	            	Diff:
            	            	--- Expected
            	            	+++ Actual
            	            	@@ -1,2 +1,2 @@
            	            	-{Kunming=19.8/19.8/19.8}
            	            	+{Kunming=0.0/0.0/0.0}
            	            	 
            	Test:       	TestMain/test_cases\measurements-1
    --- FAIL: TestMain/test_cases\measurements-10 (0.01s)
       billionlinechallenge\main_test.go:18: 
            	Error Trace:	billionlinechallenge/main_test.go:18
            	Error:      	Not equal: 
            	            	expected: "{Adelaide=15.0/15.0/15.0, Cabo San Lucas=14.9/14.9/14.9, Dodoma=22.2/22.2/22.2, Halifax=12.9/12.9/12.9, Karachi=15.4/15.4/15.4, Pittsburgh=9.7/9.7/9.7, Ségou=25.7/25.7/25.7, Tauranga=38.2/38.2/38.2, Xi'an=24.2/24.2/24.2, Zagreb=12.2/12.2/12.2}\r\n"
            	            	actual  : "{Adelaide=0.0/0.0/0.0, Cabo San Lucas=0.0/0.0/0.0, Dodoma=0.0/0.0/0.0, Halifax=0.0/0.0/0.0, Karachi=0.0/0.0/0.0, Pittsburgh=84.5/84.5/84.5, Ségou=0.0/0.0/0.0, Tauranga=0.0/0.0/0.0, Xi'an=0.0/0.0/0.0, Zagreb=0.0/0.0/0.0}\n"
            	            	
            	            	Diff:
            	            	--- Expected
            	            	+++ Actual
            	            	@@ -1,2 +1,2 @@
            	            	-{Adelaide=15.0/15.0/15.0, Cabo San Lucas=14.9/14.9/14.9, Dodoma=22.2/22.2/22.2, Halifax=12.9/12.9/12.9, Karachi=15.4/15.4/15.4, Pittsburgh=9.7/9.7/9.7, Ségou=25.7/25.7/25.7, Tauranga=38.2/38.2/38.2, Xi'an=24.2/24.2/24.2, Zagreb=12.2/12.2/12.2}
            	            	+{Adelaide=0.0/0.0/0.0, Cabo San Lucas=0.0/0.0/0.0, Dodoma=0.0/0.0/0.0, Halifax=0.0/0.0/0.0, Karachi=0.0/0.0/0.0, Pittsburgh=84.5/84.5/84.5, Ségou=0.0/0.0/0.0, Tauranga=0.0/0.0/0.0, Xi'an=0.0/0.0/0.0, Zagreb=0.0/0.0/0.0}
            	            	 

`customStringToIntParser` can likely be faster using a lookup table

I had a look at https://github.com/shraddhaag/1brc/blob/8513d5e70a1bfabbf46ab86a9cb6558bc9805154/main.go#L240C6-L240C29. Given that the temperatures are always within [-99.9, 99.9] and you know that it always has a tenth of accuracy, you can build up a string -> int lookup table on startup of your application. The lookup table will hold 1999 items. That way, parsing will be looking up the string in the lookup table. My gut feeling is this will be faster.

Caveat: I have not looked at the raw data file, nor have a ran the program.

Further read optimization

Hi, first of all thank you for sharing your code!

I was quite impressed by the reading speed, and I think that I found a way to make this part a bit faster:

1brc/main.go

Lines 131 to 155 in 8513d5e

// spawn a goroutine to read file in chunks and send it to the chunk channel for further processing
go func() {
buf := make([]byte, chunkSize)
leftover := make([]byte, 0, chunkSize)
for {
readTotal, err := file.Read(buf)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
panic(err)
}
buf = buf[:readTotal]
toSend := make([]byte, readTotal)
copy(toSend, buf)
lastNewLineIndex := bytes.LastIndex(buf, []byte{'\n'})
toSend = append(leftover, buf[:lastNewLineIndex+1]...)
leftover = make([]byte, len(buf[lastNewLineIndex+1:]))
copy(leftover, buf[lastNewLineIndex+1:])
chunkStream <- toSend

Currently each loop calls 2 times make([]byte) and copy. This could be reduced to 1, by storing the leftover as a length, instead of a byte slice:

		buf := make([]byte, chunkSize)
		leftover := 0
		for {
			n, err := file.Read(buf[leftover:]) // append to the leftover
			if err != nil {
				if errors.Is(err, io.EOF) {
					break
				}
				panic(err)
			}
			toSend := buf[:leftover+n]

			lastNewLineIndex := bytes.LastIndexByte(toSend, '\n')

			buf = make([]byte, chunkSize) // prepare a new buffer for next read
			leftover = copy(buf, toSend[lastNewLineIndex+1:])

			chunkStream <- toSend[:lastNewLineIndex+1]
		}

On a sample file, this code is about 10% faster than the current version

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.