Skip to content

Commit 1b2b441

Browse files
fastmean: hoist INTEGER_RO()/REAL_RO() out of the element loops (#7914)
* fastmean: hoist INTEGER_RO()/REAL_RO() out of the element loops * Update src/fastmean.c Co-authored-by: Michael Chirico <michaelchirico4@gmail.com> * Apply suggestion from @MichaelChirico Co-authored-by: Michael Chirico <michaelchirico4@gmail.com> --------- Co-authored-by: Michael Chirico <michaelchirico4@gmail.com>
1 parent 97a4b88 commit 1b2b441

1 file changed

Lines changed: 15 additions & 12 deletions

File tree

‎src/fastmean.c‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,16 @@ SEXP fastmean(SEXP args)
4545
error(_("fastmean was passed type %s, not numeric or logical"), type2char(TYPEOF(x)));
4646
}
4747
l = LENGTH(x);
48+
const SEXPTYPE x_type = TYPEOF(x);
49+
const int *xi = x_type == REALSXP ? NULL : INTEGER_RO(x);
50+
const double *xd = x_type == REALSXP ? REAL_RO(x) : NULL;
4851
if (narm) {
49-
switch(TYPEOF(x)) {
52+
switch(x_type) {
5053
case LGLSXP:
5154
case INTSXP:
5255
for (int i=0; i<l; ++i) {
53-
if(INTEGER_RO(x)[i] == NA_INTEGER) continue;
54-
s += INTEGER_RO(x)[i]; // no under/overflow here, s is long double not integer
56+
if(xi[i] == NA_INTEGER) continue;
57+
s += xi[i]; // no under/overflow here, s is long double not integer
5558
n++;
5659
}
5760
if (n>0)
@@ -61,8 +64,8 @@ SEXP fastmean(SEXP args)
6164
break;
6265
case REALSXP:
6366
for (int i=0; i<l; ++i) {
64-
if(ISNAN(REAL_RO(x)[i])) continue; // TO DO: could drop this line and let NA propagate?
65-
s += REAL_RO(x)[i];
67+
if(ISNAN(xd[i])) continue; // TO DO: could drop this line and let NA propagate?
68+
s += xd[i];
6669
n++;
6770
}
6871
if (n==0) {
@@ -72,8 +75,8 @@ SEXP fastmean(SEXP args)
7275
s /= n;
7376
if(R_FINITE((double)s)) {
7477
for (int i=0; i<l; ++i) {
75-
if(ISNAN(REAL_RO(x)[i])) continue;
76-
t += (REAL_RO(x)[i] - s);
78+
if(ISNAN(xd[i])) continue;
79+
t += (xd[i] - s);
7780
}
7881
s += t/n;
7982
}
@@ -87,21 +90,21 @@ SEXP fastmean(SEXP args)
8790
case LGLSXP:
8891
case INTSXP:
8992
for (int i=0; i<l; ++i) {
90-
if(INTEGER_RO(x)[i] == NA_INTEGER) {UNPROTECT(1); return(ans);}
91-
s += INTEGER_RO(x)[i];
93+
if(xi[i] == NA_INTEGER) {UNPROTECT(1); return(ans);}
94+
s += xi[i];
9295
}
9396
REAL(ans)[0] = (double) (s/l);
9497
break;
9598
case REALSXP:
9699
for (int i=0; i<l; ++i) {
97-
if(ISNAN(REAL_RO(x)[i])) {UNPROTECT(1); return(ans);}
98-
s += REAL_RO(x)[i];
100+
if(ISNAN(xd[i])) {UNPROTECT(1); return(ans);}
101+
s += xd[i];
99102
}
100103
s /= l;
101104
if(R_FINITE((double)s)) {
102105
for (int i=0; i<l; ++i) {
103106
// no NA if got this far
104-
t += (REAL_RO(x)[i] - s);
107+
t += (xd[i] - s);
105108
}
106109
s += t/LENGTH(x);
107110
}

0 commit comments

Comments
 (0)