One Billion Row Challenge Shows Java Can Process 1B Rows File in 2 Seconds
infoq.com
infoq.com
Based on the trends of "<something something> so we rewrote our entire production stack in rust!" I am surprised there is not already a comment here!
I'd also be interested in how fast JavaScript/V8 executes by comparison.
What you mention from Rust is this: https://github.com/RagnarGrootKoerkamp/1brc/ The author says himself that his solution is not compliant in the readme.
So far the top place is not clear. .NET with noahfalk, C/C++ from lehuyduc, dzaima and austindonisan require more tests. The last looks the fastest so far on the default dataset, but has issues.
Here is my blog post with details: https://hotforknowledge.com/2024/01/13/1brc-in-dotnet-among-...
CLR performance can be considered nondeterministic given it JITs and performs profile-guided-optimizations - unless you go with AOT, but there's still going to be an initialization delay, and differences in cold vs. warm. vs hot-start scenarios. In order to be fair to all languages/platforms/runtimes involved, how is that managed?
Why would you use Javascript for that?
1: https://www.reddit.com/r/rust/comments/18ws370/optimizing_a_...
Maybe 2 hours of coding, tops
https://rmoff.net/2024/01/03/1%EF%B8%8F%E2%83%A3%EF%B8%8F-1b...
https://github.com/gunnarmorling/1brc/discussions/categories...
I like this discussion because while the original is about "what can you do in 2024 stock java", I'm more interested in "what can you do if you use naive, obvious solutions". AWK does this in 6 minutes but, as pointed in this comment:
https://github.com/gunnarmorling/1brc/discussions/171#discus...
> It's either 6 minutes with 20 lines of AWK written in five minutes. Or 6 seconds in 300 lines of java written in five days. Classic "XKCD: Is It Worth the Time?".
It's exactly this. Is it going to be run many times or just once or a few times? Is it going to be run in production where it impacts customers or runs up the AWS bill? If it's a throwaway script, the Linux terminal and some Awk is hard to beat. There are always tradeoffs.
Or use the awk one in production if you want. Nothing wrong with awk ;)
Not quite, it runs in 3 minutes written in java in 5 minutes. The official baseline is quite simple and runs in about ~3min https://github.com/gunnarmorling/1brc/blob/main/src/main/jav...
I think it's also more readable than the awk for people who don't already know the language whilst being of a similar length, but that might be just me. More usefully you can get type checking, autocompletion, use any libraries you want and so on.
class Result(var lo: Double = Double.MAX_VALUE, var hi: Double = Double.MIN_VALUE, var total: Double = 0.0, var samples: Int = 0) {
val mean get() = total / samples
}
val results = HashMap<String, Result>()
Path("measurements.txt").useLines { it
.map { it.substringBefore(";") to it.substringAfter(";").toDouble() }
.forEach { (name, measurement) ->
with(results.getOrPut(name) { Result() }) {
lo = min(lo, measurement)
hi = max(hi, measurement)
total += measurement
samples++
}
}
}
results.toSortedMap().mapValues { (_, m) -> "%.1f/%.1f/%.1f".format(m.lo, m.mean, m.hi) }.also(::println)
You can do this sort of thing with jbang, although for some reason Gunnar's baseline is slower. Maybe I'm doing something wrong.I suspect it's because the baseline code is adding each line to a TreeMap before processing, effectively sorting 1B rows and then processing them. Your code reduces to the 413 unique stations and then sorts those.
I feel like Gunnar purposefully wrote the baseline with lots of room for improvement to encourage participation.
Your Kotlin code feels more imperative to me even though I'm used to that kind of things; I like that awk still feels more like describing stuff, but that's only me.
Path("measurements.txt")
.readLines()
.groupBy({ it.substringBefore(';') }, { it.substringAfter(';').toDouble() })
.forEach { (name, temps) ->
println("%s=%.1f/%.1f/%.1f".format(name, temps.min(), temps.average(), temps.max()))
}
I didn't do it that way because with one billion rows, it runs out of memory. The imperative version that mutates in place doesn't.You can probably write a functional version that also doesn't run out of memory using .groupingBy{}, because it all applies to lazy sequences. I just didn't bother working out how. The Java streams framework can do the same things and has the advantage that it can sometimes make it easy to parallelize.
¯\_(ツ)_/¯Reminds me of the code that Microsoft produced when they were trying to prove their new .NET Core is one of the fastest web runtimes - it was quite fast, but had nothing to do with the way C# code is written out there.
I'm not necessarily disagreeing, but can you elaborate on why it's better? Using unsafe for some parts of the code doesn't throw out safety guarantees about all of the rest of the code.
That's actually hard to prove because you don't know which guarantees the unsafe code can break; being unsafe, it could potentially, say, mutate arbitrary final fields of any object in the program. So while such code doesn't necessarily break invariants, there's no easy way to tell whether and which it does. Once unsafe is used, no guarantee can be fully trusted.
But the direction we're going with "integrity by default" (https://openjdk.org/jeps/8305968) is that the application will need to acknowledge and approve the use of unsafe code by libraries, and so the author of the application could choose to more closely inspect the unsafe code and try to determine its blast radius.
The current fastest safe version: https://github.com/gunnarmorling/1brc/blob/main/src/main/jav...
In fact, given that the top safe result was very close to the top unsafe result (especially considering the standard deviation), it looks like you need to write truly exceptional code to feel the cost of the random-access bounds checks. So it doesn't seem wild at all that the default is to give everyone safety at the expense of a performance cost that will only be felt by very few (and who can then enable unsafe code if they feel they need that last extra boost).
You've posted that users can use unsafe to avoid the bounds checks, but you're posting specifically about methods provided for MemorySegment that have no equivalent for Unsafe, so you're just incorrect.
"Only for random access" is probably also incorrect. We could maybe have a look at the codegen for any of the top openjdk submissions which currently perform sequential access but increment the read pointer by ctz(movemask(eq(*ptr, c)))+k at each step. It's trivial for a person to prove that the bounds checks are redundant with the loop termination condition given the MemorySegment's length and given that ctz is at most 64, but it seems unlikely that the runtime manages it. It is of course also trivial for a person who knows that the MemorySegment is so large that it only disallows addresses that differ from allowed addresses by up to two bits not used for addressing to prove that all possible addresses are allowed, or at least that they address memory which is allowed to be accessed by a different address if the user masks off the high two bits first.
That's why safe code can't obtain such a MS in the first place. To get such a segment you have to use a flag (enable-native-access) that enables unsafe operations. We're contemplating offering a MS without bounds checks in those cases (for off-heap only), but that depends on how much that would be useful.
> you're posting specifically about methods provided for MemorySegment that have no equivalent for Unsafe
I'm talking about unsafe code, not the Unsafe class specifically. The internal vector intrinsics don't perform bounds checks.
> but it seems unlikely that the runtime manages it
We're doing okay and, as always, we expect to improve.
Anyway, my point is that the top safe result was so far ahead of most submissions, that it's clearly not "wild" to prioritise safety given how few manage to get to the point where unsafety can buy them a significant boost. It also allows us to trust more invariants and perform more optimisations (once we complete "integrity by default") so that the overall performance impact is clearly positive.
VECTOR_ACCESS_OOB_CHECK controls some bounds checks performed by ByteVector.rearrange and similar methods. With these bounds checks enabled, ByteVector.rearrange costs ~40x more than pshufb rather than only ~30x more.
This comment of mine is pedantic and silly. Of course I agree there aren't any bounds checks on the memory addresses you access if you are using the intrinsics that don't access memory.
Improving performance demands that there would be no non-delineated code that could result in miscompilation or undefined behaviour. We don't want to tell people, well, we've introduced a new default optimisation but it means that it's possible that some transitive dependency you may not even know about could result in undefined behaviour. That might be okay for C (where deep dependency graphs are very, very rare), but it's certainly not what people want from Java.
Is there anything else you wanted to know and I didn't answer?
[1]: You may ask, why that universal MS doesn't disable bounds checking, and the answer is that it complicates the implementation, but a specialised MS could do it.
It probably won't make much difference on this problem for various reasons, but normally that's the case.
That being said, there is no official word but two globally used scales.
https://en.wikipedia.org/wiki/Long_and_short_scales#Current_...
See Wikipedia:
> This is now the most common sense of the word in all varieties of English; it has long been established in American English and has since become common in Britain and other English-speaking countries as well.
https://en.wikipedia.org/wiki/Billion
There is both a long- and short- scale. Neither is more correct: https://en.wikipedia.org/wiki/Long_and_short_scales
And as much as I hate it, when communicating in public what matters is the commonly used definition of the word, even if it's different that what that word meant a few years ago.
Who cares of Java can read 1bil "rows"? Why not describe it in terms of MB/s or something more reasonable?
Well, you should've - it's very clearly explained:
The text file has a simple structure with one measurement value per row:
Hamburg;12.0
Bulawayo;8.9
Palembang;38.8
St. John's;15.2
Cracow;12.6
...
The program should print out the min, mean, and max values per station, alphabetically ordered like so:
{
Abha=5.0/18.0/27.4,
Abidjan=15.7/26.0/34.1,
Abéché=12.1/29.4/35.6,
Accra=14.7/26.4/33.1,
Addis Ababa=2.1/16.0/24.3,
Adelaide=4.1/17.3/29.7,
...
}