【问题标题】:How to use ctime to mark starting and ending point of the program?如何使用 ctime 标记程序的起点和终点?
【发布时间】:2016-08-07 18:28:45
【问题描述】:
time_t start;
time_t no_infection;
bool time_already_set = 0;
bool infected_or_not = 0;
int not_infected_t = 0; 

我在结构中有这个变量,我想标记对象的起点和终点,而不是计算差异。

void bacteria::set_no_infection() {
    if (infected_or_not == 0) 
        no_infection = clock();
}

一开始我有

void bacteria::set_time() {
    if (infected_or_not == 1 && time_already_set!=1) {
        start = clock();
        time_already_set = 1;
    }
}

在我使用get函数测试它的程序期间,时间变量似乎没有改变

double bacteria::get_time() {
    if (infected_or_not == 1)  
        return ((clock() - start) / CLOCKS_PER_SEC);
    else
        return -1;
}
int bacteria::get_no_infection() {
    if (infected_or_not = 0)   
        return ((clock() - no_infection) / CLOCKS_PER_SEC);
    else
        return -1;
}

在主程序中我这样测试它:

while (1) {
    for (int i = 0; i < b.size() - 1; i++) {
        bactpop[i].set_no_infection();
        bactpop[i].inf(phagepop[i], bactpop[i], p);
        bactpop[i].kill_the_bacteria(b, i);
        cout << "        " << b[i].start << "    " << b[i].no_infection << endl;
    }
    cout << p.size() << " " << b.size() << endl;
}

【问题讨论】:

  • 在主程序中我这样测试它:while (1) { for (int i = 0; i

标签: c++ ctime


【解决方案1】:

我不确定,但我猜你的函数每秒被调用多次,并且由于 clock() / CLOCKS_PER_SEC 以秒为单位返回值,因此差异将为 0,因为调用是在同一秒内执行的。

如果可以使用 C++11,则使用具有微秒或 std::chrono::high_resolution_clock::now() 的 gettimeofday。

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2015-04-04
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多