Skip to content

Instantly share code, notes, and snippets.

@edefazio
Last active January 22, 2024 09:48
Show Gist options
  • Save edefazio/69858c5a1e26e38e8e0a to your computer and use it in GitHub Desktop.
Save edefazio/69858c5a1e26e38e8e0a to your computer and use it in GitHub Desktop.
using SWAR (SIMD Within A Register) in Java using general purpose registers
package swar.subword;
public class SWAR_Intro_NoComments
{
public static void main ( String[] args )
{
int x = 12345678;
int y = 9012345;
long xyCompound = as2x32BitCompound ( x, y );
areBothOdd( x , y );
areBothOdd( xyCompound );
}
public static long as2x32BitCompound ( int x, int y )
{
return ( ( 0L + x ) << 32 ) | ( ( y + 0L ) & ( -1L >>> 32 ) );
}
public static boolean areBothOdd( int x, int y )
{
return ( ( x & 1 ) == 1 ) && ( ( y & 1 ) == 1 );
}
public static final long SWAR_ODD_MASK = ( ( 1L << 32 ) + 1 );
public static boolean areBothOdd ( long xyCompound )
{
return ( xyCompound & SWAR_ODD_MASK ) == SWAR_ODD_MASK;
}
}
@edefazio
Copy link
Author

Illustration of sub-word parallelism or
SWAR (SIMD Within A Register) in Java. This example uses general purpose (64-bit) registers (not vector based registers or explicit vector instructions like AVX)

it's a contrived example to get to the heart of what SWAR and sub-word parallelism is.

In this scenario:

  • the "packing" of the 2x32-bit compound (into a 64-bit register) is "hand-rolled" using bit shifts/masks
  • the SWAR bit mask operation" is "hand-rolled", and it performs effectively (2) data operations (checking to see if the x value AND the y value are odd) simultaneously, rather than checking each (x value, y value) separately.

Although it may seem like a good deal of work to theoretically get rid of one or more simple instructions, in practice, SWAR operations can speed things up 6x-8x (since in many cases it eliminates the need for branch prediction (especially in the case of scanning big data sets)...

SWAR is an optimization that excels at "exact pattern matching" within a large dataset.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment