Repository navigation
Take a decimal scale into account - #1925
Conversation
|
@roji @YohDeadfall I think this is ready to merge unless you have some suggestions or corrections. Any thoughts? |
roji
left a comment
There was a problem hiding this comment.
Thanks for this precise work @StillLearnin. As I noted in the comments, I don't think it's acceptable perf-wise for the handler to allocate when reading every single decimal (decimalGetBits()). A minor CPU processing cost is OK - even if the perf cost of the new Math.Pow() and Math.Round(ModpointRounding.AwayFromZero) needs to be measured - but allocations have a much higher impact on general application performance, since they create GC pressure.
If this were really necessary for correctness, that's one thing. However, here we're proposing an allocation on every decimal read just in order to have the proper number of zeros, which is mainly important for display purposes - so I'm not very happy with that.
You may be able to eliminate the GetBits() call by looking at the type modifier as I previously proposed, I'm not sure. But I'd like to avoid the allocations in the current state of this PR.
| //midpoint rounding is AwayFromZero instead of ToEven https://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx | ||
| //This is necessary to match psql. | ||
| var rounding = new Tuple<string, decimal>[] { | ||
| new Tuple<string,decimal>("'1'::numeric(10,2)", 1.00M), //test scale |
There was a problem hiding this comment.
This test needs to be cleaned up and possibly split into several ones... It starts with a check on 1234567.890123 that is very similar to what you've added here (so the two need to be merged).
Instead of having an array of Tuple, it's better to have a separate test with TestCases (see
for an example).Also, in general the Tuple class is a little obsolete ever since C# 7 introduced value tuples with integrated syntax in C#.
There was a problem hiding this comment.
Good points, I can do that.
There was a problem hiding this comment.
nit: spaces after commas
There was a problem hiding this comment.
@YohDeadfall sure enough! Can hardly believe I missed that. At first I thought you meant there shouldn't be spaces after commas...
There was a problem hiding this comment.
@roji I have a little time today after all. Does the latest commit of tests seem acceptable?
There was a problem hiding this comment.
Is it same as NumericScaleCasting? If yes, remove it.
| throw new NpgsqlSafeReadException(new InvalidCastException("Numeric NaN not supported by System.Decimal")); | ||
|
|
||
| result = Math.Round(result, dscale); | ||
| var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result |
There was a problem hiding this comment.
decimal.GetBits() always allocates an int[], which is really not good.
There was a problem hiding this comment.
Do you have a suggestion on a better way to do it? See my other comments (coming soon) on why I believe trailing zeros aren't just a cosmetic issue.
There was a problem hiding this comment.
Use the following struct to store result and to do dirty magic:
[StructLayout(LayoutKind.Explicit)]
ref struct DecimalRaw
{
internal const int SignMask = unchecked((int)0x80000000);
internal const int ScaleMask = 0x00FF0000;
internal const int ScaleShift = 16;
[FieldOffset(0)]
internal decimal Value;
[FieldOffset(0)]
internal int Flags;
[FieldOffset(4)]
internal int Hi;
[FieldOffset(8)]
internal int Lo;
[FieldOffset(12)]
internal int Mid;
}var rscale = (result.Flags & DecimalRaw.ScaleMask) >> DecimalRaw.ScaleShift;There was a problem hiding this comment.
@YohDeadfall I assume you're recommending a struct for result storage because it will be stored on the stack instead of the heap. This allows us to read the result scale which is then stored in rscale, also on the stack as a simple integer value.
Since popping the stack is much faster than garbage collection, we avoid a lot of overhead.
Did I get it right?
P.S. Most of my work has not needed to be so performance critical so I'm still learning this stuff.
There was a problem hiding this comment.
Yep, you're right, except one thing. Overhead is not in popping, but in memory allocation on the heap. GetBits allocates an array of four integers.
Don't worry about that. I'll help you with perf optimizations.
There was a problem hiding this comment.
Shouldn't the FieldOffset for Mid and Lo be
[FieldOffset(8)]
internal int Mid;
[FieldOffset(12)]
internal int Lo;Instead of
[FieldOffset(8)]
internal int Lo;
[FieldOffset(12)]
internal int Mid;| var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result | ||
|
|
||
| if (rscale < dscale) //If result scale is insufficient, | ||
| result = result * new decimal((int)Math.Pow(10, dscale), 0, 0, false, 2); //increase it. |
There was a problem hiding this comment.
So in the end we don't have to look at the type modifier to know what scale to round to?
There was a problem hiding this comment.
That is right. My original understanding that dscale was the scale of the data rather than the scale of the column was incorrect.
There was a problem hiding this comment.
Math.Pow is a perf killer. Use a table of predefined values (powers of 10).
static readonly decimal[] Powers10 =
{
1M,
10M,
100M,
1000M,
10000M,
100000M,
1000000M,
10000000M,
100000000M,
1000000000M,
10000000000M,
// And so on. You should totally have 29 powers of 10.
};result.Value *= new DecimalRaw { Value = Powers10[scale - resultScale], Flags = (scale - resultScale) << DecimalRaw.ScaleShift }.Value;It's okay to have 1000000000 as the max value in the table and to store ints in it, but then you should implement a method to produce a DecimalRaw value with the required scale.
I respectfully disagree. decimal is a type with 28 - 29 significant digits. Significant digits (which include trailing zeros in the decimal portion) are important in mathematical calculations and are used to specify exactly to what scale the measurement was done. If an actual value of 1.2 is stored in a column that has a scale of 2, that means the data is assumed to be verified to be 1.20 and we should return 1.20 not 1.2 or 1.2000 even though the values are the same. The whole point of Without this fix or a better one, it is impossible to use postgresql's cast methods. For instance, This was the simplest method for consistently achieving the correct result that I could come up with in the amount of time I had available. It could probably be improved in terms of performance. @YohDeadfall do you have time to weigh in with a benchmark? I won't have time to work on this till next week. |
|
I'm sorry this is more complicated than it seemed (and I appreciate your work), I'm not trying to complicate the situation or prevent improvements - just make sure the right decisions are being made as a whole.
That's an interesting and valid point, at least for some use cases of decimal/numeric. I'd venture to say that in most scenarios trailing zeros aren't actually important - but that's just my unfounded opinion (the main supporting fact is that people have hardly complained up to now). The main point of On the other hand, to argue against myself, C# But in any case, I do agree that there's value in preserving trailing zeros based on the column definition - the only question is perf cost. My problem is not really with CPU perf (i.e. the I don't have a lot of time to look into avoiding this, but the answer is likely that we shouldn't parse the PostgreSQL data in the first loop, and then try to apply scale properly. Instead, the required scale should probably be taken into account in the loop, as you're parsing the PostgreSQL data. Hopefully someone will have a bit of time to invest on this, otherwise I might be able to take a look at some point (but not necessarily for 4.0). |
|
Another direction is to look at how PostgreSQL itself decodes decimal in C and see what we can learn from that. |
|
No problem. A discussion like this is important to keep the code from becoming bloated and slow. I'm new to this project and you have a significant amount of time invested into it. I'm not offended at your slowness to "just accept" code from someone you've never met and haven't yet had the opportunity to build confidence in.
This is precisely where my mind was going and several times in my research into this topic I almost tackled it that way. I'll try to look into it next week. |
|
Thanks for your understanding... One of the primary focuses of 4.0 is performance (it even got a mention in Build a couple days ago) so I'm particularly careful with that. There's also a clear, growing realization of the adverse perf impact of heap allocations and the importance of keeping them down as much as possible.
OK great, good luck. The RTM release isn't supposed to happen until at least the end of the month so there's still time. |
|
Congrats on the positive reference at build! |
| throw new NpgsqlSafeReadException(new InvalidCastException("Numeric NaN not supported by System.Decimal")); | ||
|
|
||
| result = Math.Round(result, dscale); | ||
| var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result |
There was a problem hiding this comment.
Use the following struct to store result and to do dirty magic:
[StructLayout(LayoutKind.Explicit)]
ref struct DecimalRaw
{
internal const int SignMask = unchecked((int)0x80000000);
internal const int ScaleMask = 0x00FF0000;
internal const int ScaleShift = 16;
[FieldOffset(0)]
internal decimal Value;
[FieldOffset(0)]
internal int Flags;
[FieldOffset(4)]
internal int Hi;
[FieldOffset(8)]
internal int Lo;
[FieldOffset(12)]
internal int Mid;
}var rscale = (result.Flags & DecimalRaw.ScaleMask) >> DecimalRaw.ScaleShift;| var rscale = ((decimal.GetBits(result)[3] >> 16) & 0x7F); //Find scale of result | ||
|
|
||
| if (rscale < dscale) //If result scale is insufficient, | ||
| result = result * new decimal((int)Math.Pow(10, dscale), 0, 0, false, 2); //increase it. |
There was a problem hiding this comment.
Math.Pow is a perf killer. Use a table of predefined values (powers of 10).
static readonly decimal[] Powers10 =
{
1M,
10M,
100M,
1000M,
10000M,
100000M,
1000000M,
10000000M,
100000000M,
1000000000M,
10000000000M,
// And so on. You should totally have 29 powers of 10.
};result.Value *= new DecimalRaw { Value = Powers10[scale - resultScale], Flags = (scale - resultScale) << DecimalRaw.ScaleShift }.Value;It's okay to have 1000000000 as the max value in the table and to store ints in it, but then you should implement a method to produce a DecimalRaw value with the required scale.
| //midpoint rounding is AwayFromZero instead of ToEven https://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx | ||
| //This is necessary to match psql. | ||
| var rounding = new Tuple<string, decimal>[] { | ||
| new Tuple<string,decimal>("'1'::numeric(10,2)", 1.00M), //test scale |
There was a problem hiding this comment.
nit: spaces after commas
| { | ||
| using (var conn = OpenConnection()) | ||
| { | ||
| using (var cmd = new NpgsqlCommand($"SELECT {sql}", conn)) |
There was a problem hiding this comment.
You can write the first using without curly brackets to decrease indentation.
using (var conn = OpenConnection())
using (var cmd = new NpgsqlCommand($"SELECT {sql}", conn))
{
}| [TestCase("'-1.5'::numeric(10,0)", "-2", TestName = "RoundNegativeOddUp")] | ||
| [TestCase("'-2.4'::numeric(10,0)", "-2", TestName = "RoundNegativeEvenDown")] | ||
| [TestCase("'-2.5'::numeric(10,0)", "-3", TestName = "RoundNegativeEvenUp")] | ||
| public void NumericScaleCasting(string sql, string expected) |
There was a problem hiding this comment.
Any reason for expected to be a string instead of a decimal directly?
There was a problem hiding this comment.
yup. decimal is not a constant type and can't be used where a constant expression is required.
There was a problem hiding this comment.
How do you mean? You can have decimal literals with m, and the compiler seems to accept [TestCase(8m)] just fine...
There was a problem hiding this comment.
@roji Nope, it will cause CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type. It's not a primitive type.
There was a problem hiding this comment.
Sorry about that, no red squgglies in Rider for some reason but you're right that it doesn't compile. Here's an article by Jon Skeet that goes a bit deep into this.
@roji Is that Npgsql 4.0 you're talking about? Is there a list of what's to be done yet? |
|
@StillLearnin yep, the 4.0 RTM. The idea is to release at the same time as Microsoft releases 2.1 (.NET Core, Entity Framework Core), which should be around the end of the month, maybe a bit later. There isn't a huge amount to be done, you can take a look at the issue list. Aside from two somewhat large things, the idea is to stabilize and fix bugs (we did release an RC after all). |
…he 4 place chunks coming from pgsql.
| var overflow = false; | ||
|
|
||
| var result = 0M; | ||
| var result = new DecimalRaw() { Value = 0M }; |
There was a problem hiding this comment.
You can remove { Value = 0M } because it's already initialized to 0. Use new DecimalRaw() or default(DecimalRaw).
|
@YohDeadfall ready for you to perf test. |
@YohDeadfall thanks for the pointer. Will do. |
Benchmark [Config(typeof(Config))]
public class NumericPerf
{
readonly NpgsqlConnection _conn;
readonly NpgsqlCommand _cmd;
readonly NpgsqlDataReader _reader;
public NumericPerf()
{
_conn = BenchmarkEnvironment.OpenConnection();
_cmd = new NpgsqlCommand("SELECT '1.25'::numeric(10,1), '1.24'::numeric(10,1), '1.2'::numeric(10,2), '1.2'::numeric(10,3), '1.2'::numeric(10,4), '1.2'::numeric(10,5)", _conn);
_reader = _cmd.ExecuteReader();
_reader.Read();
}
[Benchmark]
public void RoundUp() => _reader.GetFieldValue<decimal>(0);
[Benchmark]
public void RoundDown() => _reader.GetFieldValue<decimal>(1);
[Benchmark]
public void ExpandScale2() => _reader.GetFieldValue<decimal>(2);
[Benchmark]
public void ExpandScale3() => _reader.GetFieldValue<decimal>(3);
[Benchmark]
public void ExpandScale4() => _reader.GetFieldValue<decimal>(4);
[Benchmark]
public void ExpandScale5() => _reader.GetFieldValue<decimal>(5);
class Config : ManualConfig
{
public Config() => Add(StatisticColumn.OperationsPerSecond);
}
}BeforeBenchmarkDotNet=v0.10.14, OS=Windows 10.0.16299.431 (1709/FallCreatorsUpdate/Redstone3)
Intel Core i7-4720HQ CPU 2.60GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
Frequency=2533212 Hz, Resolution=394.7557 ns, Timer=TSC
[Host] : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0 [AttachedDebugger]
DefaultJob : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0
AfterBenchmarkDotNet=v0.10.14, OS=Windows 10.0.16299.431 (1709/FallCreatorsUpdate/Redstone3)
Intel Core i7-4720HQ CPU 2.60GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
Frequency=2533212 Hz, Resolution=394.7557 ns, Timer=TSC
[Host] : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0 [AttachedDebugger]
DefaultJob : .NET Framework 4.6.1 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2650.0
|
|
@roji I think it is ready for your review again. Thanks for your patience and input. |
roji
left a comment
There was a problem hiding this comment.
Looks much better, @StillLearnin thanks for the great work and @YohDeadfall thanks for the valuable guidance.
@YohDeadfall feel free to merge, I'll add a note to the release notes.
|
Thanks, added a line in the release notes. |
No description provided.