Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know this is highly unportable but x86 assembler instruction <em>bswap</em> lets you swap four bytes by means of just one instruction which can be a good path to boost the code.</p> <p>This is an example of how to get it working with GCC.</p> <pre><code>/* * reverse.c * * $20081020 23:33 fernando DOT miguelez AT gmail DOT com$ */ #include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #define MAX_CHARS 10 * 1024 * 1024 /* * Borrowed from http://coding.derkeiler.com/Archive/Assembler/comp.lang.asm.x86/2007-03/msg00004.html * GNU Compiler syntax */ inline uint32_t bswap(uint32_t val) { __asm__("bswap %0" : "=r" (val) : "0" (val)); return val; } char * reverseAsm(const char * str) { int i; int length = strlen(str); int dwordLength = length/4; if(length % 4 != 0) { printf("Error: Input string length must be multiple of 4: %d\n", length); return NULL; } char * reversed_string = (char *) malloc(length+1); for(i = 0; i &lt; dwordLength; i++) { *(((uint32_t *) reversed_string) + dwordLength - i - 1) = bswap(*(((uint32_t *) str) + i)); } reversed_string[length] = '\0'; return reversed_string; } char * reverse(const char * str) { int i; int length = strlen(str); char * reversed_string = (char *) malloc(length+1); for(i = 0; i &lt; length; ++i) { reversed_string[i] = str[(length-1) - i]; } //need to null terminate the string reversed_string[length] = '\0'; return reversed_string; } int main(void) { int i; char *reversed_str, *reversed_str2; clock_t start, total; char *str = (char *) malloc(MAX_CHARS+1); str[MAX_CHARS] = '\0'; srand(time(0)); for(i = 0; i &lt; MAX_CHARS; i++) { str[i] = 'A' + rand() % 26; } start = clock(); reversed_str = reverse(str); total = clock() - start; if(reversed_str != NULL) { printf("Total clock ticks to reverse %d chars with pure C method: %d\n", MAX_CHARS, total); free(reversed_str); } start = clock(); reversed_str2 = reverseAsm(str); total = clock() - start; if(reversed_str2 != NULL) { printf("Total clock ticks to reverse %d chars with ASM+C method: %d\n", MAX_CHARS, total); free(reversed_str2); } free(str); return 0; } </code></pre> <p>The results on my old computer under Cygwin:</p> <pre><code>fer@fernando /cygdrive/c/tmp$ ./reverse.exe Total clock ticks to reverse 10485760 chars with pure C method: 221 Total clock ticks to reverse 10485760 chars with ASM+C method: 140 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload