如何使用ctime来标记程序的起点和终点

How to use ctime to mark starting and ending point of the program?

本文关键字:起点 终点 程序 何使用 ctime      更新时间:2023-10-16
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;
}

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

例如,如果可以使用C++11,则使用gettimeofday(以微秒为单位(或std::chrono::high_resolution_clock::now((。