Skip to content

Commit

Permalink
A few perf tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
flanglet committed Jan 18, 2024
1 parent 707852a commit a886cf3
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions java/src/main/java/kanzi/entropy/EntropyUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public static int normalizeFrequencies(int[] freqs, int[] alphabet, int totalFre
{
final int delta = (int) (sumScaledFreq-scale);

if (Math.abs(delta) * 20 < freqs[idxMax])
if (Math.abs(delta) * 10 < freqs[idxMax])
{
// Fast path (small error): just adjust the max frequency (or fallback to the slow path)
if (freqs[idxMax] > delta)
Expand All @@ -211,15 +211,21 @@ public static int normalizeFrequencies(int[] freqs, int[] alphabet, int totalFre
}

// Slow path: spread error across frequencies
final int inc = (sumScaledFreq > scale) ? -1 : 1;
final int inc = (delta > 0) ? -1 : 1;
LinkedList<FreqSortData> queue = new LinkedList<>();

for (int i=0; i<alphabetSize; i++)
{
if (freqs[alphabet[i]] != -inc)
if (freqs[alphabet[i]] >= 2) // Do not distort small frequencies
queue.add(new FreqSortData(freqs, alphabet[i]));
}

if (queue.isEmpty())
{
freqs[idxMax] -= delta;
return alphabetSize;
}

Collections.sort(queue);

while (sumScaledFreq != scale)
Expand Down

0 comments on commit a886cf3

Please sign in to comment.