Created
November 7, 2017 20:31
-
-
Save romainfrancois/3254264b34100cda40846f9e1fbe29c9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Rcpp.h> | |
using namespace Rcpp ; | |
// [[Rcpp::plugins(cpp11)]] | |
inline uint64_t as_uint64_t(double x){ | |
return *reinterpret_cast<uint64_t*>( &x ) ; | |
} | |
inline uint64_t quiet_na(){ | |
return as_uint64_t(NA_REAL) ; | |
} | |
inline uint64_t signaling_na(){ | |
return as_uint64_t(NA_REAL + 1); | |
} | |
inline uint64_t na_mask(){ | |
return ~( signaling_na() - quiet_na() ) ; | |
} | |
// [[Rcpp::export]] | |
int sum_is_na( NumericVector x ){ | |
// a quiet NA, as a uint64_t | |
uint64_t na = quiet_na() ; | |
// mask (binary representation of (signaling NA) - (quiet NA)) | |
uint64_t mask = na_mask() ; | |
return std::count_if( | |
reinterpret_cast<uint64_t*>(x.begin()), | |
reinterpret_cast<uint64_t*>(x.end()), | |
[na,mask]( uint64_t value ){ | |
return (value & mask) == na ; | |
} | |
) ; | |
} | |
inline double as_double( uint64_t x){ | |
return *reinterpret_cast<double*>( &x ) ; | |
} | |
// [[Rcpp::export]] | |
double NA_mask(){ | |
return as_double(na_mask()) ; | |
} | |
/*** R | |
seven31::reveal( NA, NA+1, NA_mask() ) | |
library(microbenchmark) | |
bench <- function(n = 1e6){ | |
x <- rnorm(n) | |
x[ sample(n, n/10) ] <- NA | |
microbenchmark( | |
sum(is.na(x)), | |
sum_is_na(x) | |
) | |
} | |
bench(1e6) | |
*/ |
Author
romainfrancois
commented
Nov 7, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment