计算函数执行的时间

2020-05-21  本文已影响0人  执拗的男孩
方法1
double func_runtime(double last, char* key) {
    clock_t now = clock();
    printf("time:%fs \t key:%s \n", (last != 0) ? (double)(now - last) / CLOCKS_PER_SEC : 0, key);
    return now;
}

    double t = func_runtime(0, "");
    func_runtime(t, "end");
方法2
#ifndef NonAtomicTest_Method_h

#define NonAtomicTest_Method_h

//c函数实现  返回值类型 函数名  函数参数(是一个block)

CGFloat BNRTimeBlock (void (^block)(void)) {
    mach_timebase_info_data_t info;
    if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;
    uint64_t start = mach_absolute_time ();

    block ();

    uint64_t end = mach_absolute_time ();

    uint64_t elapsed = end - start;

    uint64_t nanos = elapsed * info.numer / info.denom;

    return (CGFloat)nanos / NSEC_PER_SEC;

} // BNRTimeBlock

#endif

    CGFloat time = 0.0 ;
    printf("begin:===========%lf\n",time);
    time = BNRTimeBlock(^{
        printf("end2:===========%lf\n",time);

        });
        printf("end1:===========%lf\n",time);

上一篇下一篇

猜你喜欢

热点阅读