【问题标题】:Need Help in Faster Algorithm and Code-checking - comparing values to database data在更快的算法和代码检查方面需要帮助 - 将值与数据库数据进行比较
【发布时间】:2012-09-25 14:45:15
【问题描述】:

我需要帮助来开发一种更快的算法,以便在我的 CGI 文件中使用(使用 C)。我有四个 sqlite3 数据库表,其中包含两个参数攻击类型和防御类型。这些表是 mod_no、mod_ne、mod_av 和 mod_se。当函数double modifier(int attack_type, int defend) 时,如果其中一个表中同时存在attack_type 和defend_type 的条目,则sqlite3 语句从数据库中进行选择。根据 sqlite3 语句产生的表 == 1,函数将返回数据类型 double 的特定值。

代码如下:

double modifier(int attack_type, int defend_type)
{
    sqlite3 *conn;
    sqlite3_stmt *res;
    sqlite3_open("MP1.sl3", &conn);
    int i,n;
    int eff;
    char    temp[MAXLENGTH];
    char    mod_tables[4][8] = {"mod_no","mod_ne","mod_av","mod_se"};
    for (i = 0; i <=3; i++) {
        printf(temp, "select exists(select atk_typ,pok_typ from %s where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ);
        sqlite3_prepare_v2(conn,temp,MAXLENGTH,&res,NULL);
        while(sqlite3_step(res) != SQLITE_ROW) {
            n = sqlite3_column_int(res,0);
        }
        sqlite3_finalize(res);
        if (n == 1) eff = i;
        if (eff == i) break;

    }
    sqlite3_close(conn);
    return eff/(double)2;   
}

这段代码的问题是(1)它不返回任何值,以及(2)它很慢。为了测试问题是否出在代码上,我初始化了eff = 2,使函数返回1。CGI 文件运行得很快。但是当我删除初始值时,它又变慢了。

我需要有一个工作功能。我做错了什么?

【问题讨论】:

    标签: c algorithm sqlite cgi


    【解决方案1】:

    这是一种可能的优化:

    select exists(select atk_typ,pok_typ from mod_no where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ)
    union
    select exists(select atk_typ,pok_typ from mod_ne where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ)
    union
    select exists(select atk_typ,pok_typ from mod_av where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ)
    union
    select exists(select atk_typ,pok_typ from mod_se where atk_typ = %d and pok_typ = %d);",mod_tables[i],atk_typ, pok_typ)
    

    那么你只有 1 个查询并且可以摆脱外部 for 循环。

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多