简体   繁体   中英

Prefetching double class member requires casting to char*?

I have a class which I am using _mm_prefetch() to pre-request the cacheline containing a class member, of type double:

class MyClass{

    double getDouble(){
        return dbl;
    }

    //other members
    double dbl;
    //other members
};

_mm_prefetch() signature is:

void _mm_prefetch (char const* p, int i)

But when I do:

_mm_prefetch((char*)(myOb.getDouble()), _MM_HINT_T0);

GCC complains:

error: invalid cast from type 'double' to type 'char*'

So how do I prefetch this class member?

If you read the description for _mm_prefetch() from the site you linked to it has :

void _mm_prefetch (char const* p, int i)

Fetch the line of data from memory that contains address p to a location in the cache heirarchy specified by the locality hint i.

So you need to pass the address of the variable that you want. In order for you to do that you need to pass to the function either the address of a reference to the class member or a pointer to it.

The simplest solution woul be to change getDouble() to return a reference and then you can use:

_mm_prefetch((char*)(&myOb.getDouble()), _MM_HINT_T0);

_mm_prefetch loads a cache line at a memory addresses into the cache. Trying to cast a double to a pointer doesn't work, as they are not compatible types. Also, you cannot simply call _mm_prefetch on the address of the return value of getDouble, as it's not going to be the address of the instance you're looking for, it will be the address of a local or temporary (which is presumably already 'close' to the processor). Also, the act of simply calling getDouble will load the address, because you are accessing the member within the function.

Most likely, your best option (depending on the size of MyClass and your target's cache line size) is to load the entire object into the cache, like so:

_mm_prefetch(&myOb, _MM_HINT_T0);

Prefetching is also generally most effective when you can do it somewhat in advance of the operation you're performing on the memory address. For example, doing:

_mm_prefetch(&myOb, _MM_HINT_T0);
myObj.getDouble();

Will not benefit performance (in fact, it may hurt it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM