(Warning:very limited expertise.)
Nothing obviously wrong leaps out from what you've posted.
But that isn't going to be any quicker to use than the equivalent Perl code:
vec( $vector, $bit, 1 ) ||= 1;
A quick test shows that it is considerably slower: use strict;
use warnings;
use Benchmark qw[ cmpthese ];
use Inline C => 'DATA';
my( $vec1, $vec2 ) = ( ( chr(0) x 125000 ) x 2 );
cmpthese -3, {
inline => sub { mytest( $vec1, $_ ) for 0 .. 1e6-1; },
vec => sub { vec( $vec2, $_, 1 ) ||= 1 for 0 .. 1e6-1; },
};
warn "Different results" unless $vec1 eq $vec2;
__DATA__
__C__
int mytest(SV* sv_vec, unsigned int bit) {
STRLEN vecbytes; // Length of vector in bytes
unsigned char *myvec = (unsigned char *) SvPV(sv_vec, vecbytes);
if (bit/8 >= vecbytes) return 0; // Check in range
if (myvec[bit/8] & 1U<<(bit%8)) return 1; // Test if a bit is set
myvec[bit/8] |= 1U<<(bit%8); // Set bit (CHANGES $vector)
return 1;
}
Results: C:\test>903727.pl
Rate inline vec
inline 3.11/s -- -60%
vec 7.77/s 150% --
C:\test>903727.pl
Rate inline vec
inline 3.10/s -- -60%
vec 7.77/s 151% --
You mention in a later post that "The real case applies some fairly complex logic to multiple large bit vectors (each 1m+ bits) which runs a lot faster in C.". That raises a couple of questions:
- If the real code is so complex, why are you asking us to make judgements based on such a trivial example that can never meet its stated goal of greater efficiency?
- The way you've asked the question suggests that you are unsure about the parameter handling rather than the actual internal logic. Where exactly do your doubts lie?
Update: There is also the question of why you are setting the bit conditionally? That is, your calling code will never be able to tell the difference between the situation where the bit was previously unset; and when it was already set.
So why bother testing if it is set and not just set it?
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|