Last active
August 29, 2015 14:02
-
-
Save kimhunter/5835fd4dfd1b95a4046f to your computer and use it in GitHub Desktop.
timed comparison of nsscanner to an array split parsing task.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// Scratch | |
// | |
// Created by Kim Hunter on 12/06/2014. | |
// Copyright (c) 2014 Kim Hunter. All rights reserved. | |
// | |
// Here I do similar test while the code does some actual task in the loops | |
// The results: the nsscanner approach takes less than a tenth of the time | |
// of the naïve array splitting result. | |
// | |
// 2014-06-13 00:21:55.608 Scratch[2309:303] 11.123 avg: 5.459 | |
// 2014-06-13 00:21:56.661 Scratch[2309:303] 1.052 avg: 0.573 | |
// Program ended with exit code: 0 | |
// | |
#import <Foundation/Foundation.h> | |
#import <QuartzCore/QuartzCore.h> | |
#define RUNS 20 | |
int main(int argc, const char * argv[]) | |
{ | |
NSString *filePath = [@"~/Desktop/scanner_test.txt" stringByExpandingTildeInPath]; | |
NSTask *t = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/touch" arguments:@[filePath]]; | |
[t waitUntilExit]; | |
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:filePath]; | |
@autoreleasepool { | |
CFTimeInterval start, end; | |
NSString *wordsString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL]; | |
double total = 0.0; | |
start = CACurrentMediaTime(); | |
for (int i = 0; i < RUNS; ++i) | |
{ | |
NSArray *a = [wordsString componentsSeparatedByString:@"\n"]; | |
for (NSString *s in a) | |
{ | |
if([s length]) | |
{ | |
[fh writeData:[NSData dataWithBytes:[s UTF8String] length:[s length]]]; | |
} | |
} | |
total += CACurrentMediaTime() - start; | |
} | |
end = CACurrentMediaTime(); | |
NSLog(@"%.3lf avg: %.3lf", end - start, total/RUNS); | |
total = 0.0; | |
start = CACurrentMediaTime(); | |
for (int i = 0; i < RUNS; ++i) | |
{ | |
NSScanner *scanner = [[NSScanner alloc] initWithString:wordsString]; | |
[scanner setCharactersToBeSkipped:nil]; | |
while (![scanner isAtEnd]) | |
{ | |
NSString *nextString = nil; | |
[scanner scanUpToString:@"\r\n" intoString:&nextString]; | |
if ([nextString length]) | |
{ | |
[fh writeData:[NSData dataWithBytes:[nextString UTF8String] length:[nextString length]]]; | |
} | |
if ([scanner isAtEnd]) | |
{ | |
break; | |
} | |
scanner.scanLocation += scanner.scanLocation; | |
} | |
total += CACurrentMediaTime() - start; | |
} | |
end = CACurrentMediaTime(); | |
NSLog(@"%.3lf avg: %.3lf", end - start, total/RUNS); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment