Category ArchiveC
C &C++ &Code &Java &Perl &PHP &Python 17 Mar 2010 09:13 pm
Language Comparison: Find Longest Line
The task: Write a portable tool that takes a file name as first argument, and from that file outputs the number of lines, the longest line, the length of the longest line, and the line number of the longest line, in a binary-safe fashion (meaning, \n is the only reason a line should be delimited; embedded \0s may occur).
My sinister side goal is showing how complex the C code has to be in order to get performance near C++. It is possible to write a simpler version in C that is 20% faster for /usr/share/dict/words, but it is then 4x slower for the random files. It would also be possible to write a faster non-portable version using memory mapping, but can’t really call that simple. C++ has both readability and speed. If I missed some obvious portable optimization in the C code, let me know…
The contestants are:
| Source | Version / Flags | Source Lines | Source Bytes |
|---|---|---|---|
| find-longest-line.c | gcc 4.3.2 -std=c99 -O3 | 77 lines | 2410 bytes |
| find-longest-line.cpp | g++ 4.3.2 -O3 | 33 lines | 964 bytes |
| find-longest-line.php | PHP 5.2.9 | 34 lines | 751 bytes |
| find-longest-line.pl | Perl 5.10.0 | 31 lines | 658 bytes |
| find-longest-line.py | Python 2.5.2 (provided by Kniht / Roger Pate) | 22 lines | 515 bytes |
| find-longest-line.cs | Mono 2.2 (provided by Windcape / Claus Jørgensen) | 45 lines | 1155 bytes |
Continue Reading »
C 31 Jan 2010 11:29 pm
Snippet: Convert Hex to Text
http://tinodidriksen.com/uploads/code/c/hex-to-text.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char buf[] = "54657374";
size_t len = strlen(buf);
if (len & 1) {
printf("Cannot take hex from odd length string.\n");
exit(1);
}
char *result = (char*)malloc(len/2 + 1);
memset(result, 0, len/2 + 1);
for (size_t i = 0 ; i < len/2 ; ++i) {
char tmp[3] = {buf[i*2], buf[i*2+1], 0};
result[i] = (char)strtol(tmp, NULL, 16);
}
printf("%s converted to %s\n", buf, result);
free(result);
return 0;
}
