pointers - C array = array faster than memcpy() -
i have piece of c code trying optimise involves setting array b. using memcpy achieve this, , works, it's not fast enough. i.e.
double a[4] = {1.0, 2.0, 3.0, 4.0}; double b[4]; memcpy(b, a, sizeof(a));
this basic example, program similar uses 9000 doubles. know use of pointers can save lot of time, i'm not sure how it. you're appreciated.
edit: don't need keep array, can discarded. need transfer b.
i use values in b determine new values a. goes through while loop checking convergence in data.
in case may able avoid copying, if switch arrays , forth, (which backwards wrote; adjust needed):
double array1[size], array2[size]; double* = array1, double* b = array2; generate_initial_values(array1); (;;) { // either memcpy(b, a, sizeof array1); // sizeof either array do; *don't* use sizeof or b, size of pointer, not of array update_values_in_b(b); // or, better: produce_modified_values_in_b_from_a(a, b); if (converged(a, b)) break; // switch arrays double* temp_ptr = a; = b; b = temp_ptr; }
doing second way faster if works you. if must memcpy, can try stuff in very fast memcpy image processing?, best use memcpy , set compiler's optimization level high possible. sure #include <string.h>
, size argument memcpy compile-time constant (it above), , @ generated assembly code verify compiler inlining copy.
edit: wait, here's thought, doesn't require switching arrays:
double a[size], b[size]; generate_initial_values(a); (;;) { produce_modified_values_in_second_array_from_first(a, b); if (converged(a, b)) break; produce_modified_values_in_second_array_from_first(b, a); if (converged(b, a)) break; }
when exit loop don't know array has latest values, if they've converged don't care. if do, can set pointer latest values, or use function:
void calling_function(void) { ... double a[size], b[size]; generate_initial_values(a); double* great_values = get_great_values(a, b); // returns either or b ... } double* get_great_values(double* a1, double* a2) { (;;) { produce_modified_values_in_second_array_from_first(a1, a2); if (converged(a1, a2)) return a2; produce_modified_values_in_second_array_from_first(a2, a1); if (converged(a2, a1)) return a1; } }
Comments
Post a Comment