[Rd] Manipulating single-precision (float) arrays in .Call functions

Simon Urbanek simon.urbanek at r-project.org
Tue Jul 19 01:53:15 CEST 2011


On Jul 18, 2011, at 6:15 PM, Alireza Mahani wrote:

> Duncan,
> 
> Thank you for your reply. This is a rather unfortunate limitation, because for large data sizes there is a significant difference between the performance of '.C' and '.Call'.

I think you may have missed the main point - R does NOT have any objects that are in "float" (single precision) representations because that is insufficient precision, so one way or another you'll have to do something like

SEXP foo(SEXP bar) {
	double *d = REAL(bar);
	int i, n = LENGTH(bar);
	float *f = (float*) R_alloc(sizeof(float), n);
	for (i = 0; i < n; i++) f[i] = d[i];
	// continue with floats ..


There is simply no other way as, again, there are no floats in R anywhere. This has nothing to do with .C/.Call, either way floats will need to be created from the input vectors.

If you make up your own stuff, you could use raw vectors to store floats if only your functions work on it (or external pointers if you want to keep track of the memory yourself).


> I will have to do some tests to see what
> sort of penalty I incur for copying from double to float inside my C++ code
> (so I can use '.Call'). I won't be able to use memset(); rather, I have to
> have an explicit loop and use casting. Is there a more efficient option?
> 

I'm not aware of any, if you use floats, you incur a penalty regardless (one for additional storage, another for converting).

One of the reasons that GPU processing has not caught much traction in stat computing is because it's (practically) limited to single precision computations (and we even need quad precision occasionally). Although some GPUs support double precision, they are still not fast enough to be a real threat to CPUs. (I'm talking about generic usability - for very specialized tasks GPU can deliver big speedups, but those require low-level exploitation of the architecture).

Cheers,
Simon



More information about the R-devel mailing list