0

我正在尝试对一些不同的算法设计进行基准测试,并且我想通过使它们在内部使用用户强制类型安全的类型不安全来概括我的功能。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void * foo1(unsigned n)
{
    unsigned i;
    unsigned long sum = 0;
    void * psum = &sum;

    for(i = 0; i < n; ++i)
        ++sum;

    return psum;
}

...

int main(void)
{
    int i;
    unsigned n;
    unsigned long sum = 0;
    void *(*foo[6])(unsigned) = {&foo1, &foo2, &foo3, &foo4, &foo5, &foo6};
    unsigned n_max[6] = {1000000001, 1000001, 10001, 1000001, 101, 1001};
    clock_t start, end;

    for(i = 0; i < 6; ++i){
        n = 1;
        do{
            start = clock();
            sum = *(unsigned long *)(*foo[i])(n);
            end = clock();
            printf("%d|%lu|%.6f\n", n, sum, (double) (end - start) / CLOCKS_PER_SEC);
            n *= 10;
        }while(n < n_max[i]);
    }

    return 0;
}

我的问题具体是关于如何使我的 foo() 函数比它们更通用,使我能够将它们用于每种类型。

为此,我有一个想法,但我不确定;如果有符号数据类型被转换为无符号,然后被任何其他无符号数据类型修改,执行的算术是否会坚持,或者会发生错误的数学?

4

0 回答 0