Reputation: 97
Consider this kind of if-statment in a function:
int Foo( void )
{
if ( HostCPUInfo::IsSSE3Supported() )
// SSE3 intrinsic
else
// C code
}
I check during the runtime if SSE3 instructions are supported by the host CPU to permit the use of faster intrinsic. But, as I doubt the the return of HostCPUInfo::IsSSE3Supported() is going to change during the life of my program, is there a way to only make this kind of checks once (maybe during the initialization) ?
Upvotes: 1
Views: 72
Reputation: 4752
You could use a function pointer that is initialized to a function that performs the test. This way, you don't have to call a special initialization function before using foo()
:
int foo_init (void);
int foo1 (void);
int foo2 (void);
int (*Foo) (void) = foo_init;
int foo_init (void)
{
Foo = (HostCPUInfo::IsSSE3Supported() ? foo1 : foo2);
return Foo();
}
...
int main (void)
{
Foo();
...
}
This might have implications for performance if the compiler is unable to inline the foo
functions.
Upvotes: 1
Reputation: 42838
Check HostCPUInfo::IsSSE3Supported()
once before entering Foo
and set some boolean depending on the return value.
Then in Foo
check only that boolean, which will always remain the same regardless of whether the return value of HostCPUInfo::IsSSE3Supported()
changes.
Upvotes: 0
Reputation: 182639
Here's one way with function pointers:
int (*foo)() = synthetic_foo;
void init() {
if (HostCPUInfo::IsSSE3Supported()) {
foo = sse3_foo;
}
}
Upvotes: 4