Created
October 5, 2016 16:11
-
-
Save yllan/62a796e8867ff16b03faf41513ddd270 to your computer and use it in GitHub Desktop.
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
// | |
// StopWatch.m | |
// FaceFront | |
// | |
// Created by Yung-Luen Lan on 05/10/2016. | |
// Copyright © 2016 Kneron. All rights reserved. | |
// | |
#import "StopWatch.h" | |
#import <Foundation/Foundation.h> | |
#include <string> | |
#include <map> | |
#include <mach/mach.h> | |
#include <mach/mach_time.h> | |
static std::map<std::string, uint64_t> totalDuration; | |
static std::map<std::string, uint64_t> sampleCount; | |
static std::map<std::string, uint64_t> beginTime; | |
void stopwatch_begin(const char *name) { | |
uint64_t start = mach_absolute_time(); | |
std::string channel = name; | |
beginTime[channel] = start; | |
sampleCount[channel]++; | |
} | |
static double convert_mach_to_second(uint64_t mtime) | |
{ | |
static mach_timebase_info_data_t sTimebaseInfo; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
mach_timebase_info(&sTimebaseInfo); | |
}); | |
return (double)mtime * sTimebaseInfo.numer / sTimebaseInfo.denom / 1000000000.0; | |
} | |
CFTimeInterval stopwatch_stop(const char *name, bool shouldLog) | |
{ | |
std::string channel = name; | |
if (beginTime.find(channel) != beginTime.end()) { | |
uint64_t end = mach_absolute_time(); | |
uint64_t elapsed = end - beginTime[channel]; | |
totalDuration[channel] += elapsed; | |
beginTime.erase(channel); | |
double current = convert_mach_to_second(elapsed); | |
double total = convert_mach_to_second(totalDuration[channel]); | |
NSLog(@"%llu timing %s: %lf seconds, total = %lf, avg = %lf.", sampleCount[channel], name, current, total, total / sampleCount[channel]); | |
return convert_mach_to_second(elapsed); | |
} else { | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment