Skip to content

Instantly share code, notes, and snippets.

@smic
Created January 8, 2012 17:28
Show Gist options
  • Save smic/1579069 to your computer and use it in GitHub Desktop.
Save smic/1579069 to your computer and use it in GitHub Desktop.
Performance test of the function hypot
//
// main.m
// HypotTest
//
// Created by Stephan Michels on 08.01.12.
// Copyright (c) 2012 Stephan Michels Softwareentwicklung und Beratung. All rights reserved.
//
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSUInteger numberOfPoints = 1000;
NSPoint points[numberOfPoints];
for (NSUInteger pointIndex = 0; pointIndex < numberOfPoints; pointIndex++) {
points[pointIndex].x = cosf((float)pointIndex / numberOfPoints * M_PI);
points[pointIndex].y = sinf((float)pointIndex / numberOfPoints * M_PI);
// NSLog(@"%lu.Point = %@", pointIndex + 1, NSStringFromPoint(points[pointIndex]));
}
NSUInteger numberOfLoops = 1000000;
CGFloat length = 0;
NSTimeInterval time = [NSDate timeIntervalSinceReferenceDate];
for (NSUInteger loopIndex = 0; loopIndex < numberOfLoops; loopIndex++) {
for (NSUInteger pointIndex = 1; pointIndex < numberOfPoints; pointIndex++) {
CGFloat dx = points[pointIndex].x - points[pointIndex - 1].y;
CGFloat dy = points[pointIndex].x - points[pointIndex - 1].y;
length += sqrtf(dx * dx + dy * dy);
}
}
time = [NSDate timeIntervalSinceReferenceDate] - time;
NSLog(@"Result %f in %f seconds (Sqrt)", length, time);
length = 0;
time = [NSDate timeIntervalSinceReferenceDate];
for (NSUInteger loopIndex = 0; loopIndex < numberOfLoops; loopIndex++) {
for (NSUInteger pointIndex = 1; pointIndex < numberOfPoints; pointIndex++) {
CGFloat dx = points[pointIndex].x - points[pointIndex - 1].y;
CGFloat dy = points[pointIndex].x - points[pointIndex - 1].y;
length += hypotf(dx, dy);
}
}
time = [NSDate timeIntervalSinceReferenceDate] - time;
NSLog(@"Result %f in %f seconds (Hypot)", length, time);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment