【问题标题】:can we get the time between two inputs?我们可以得到两个输入之间的时间吗?
【发布时间】:2014-02-07 16:53:41
【问题描述】:

我在看这段代码时想知道:

#include<iostream>
#include<conio.h>

using namespace std;

int main(){

    int a,b;

    cout << "enter 1";
    cin  >> a;

    cout << "enter 2";
     cin >> b;

    getch();
    return 0;
}  

如果我们能连续得到变量a和b的输入之间的时间间隔。

【问题讨论】:

    标签: c++ input time cin


    【解决方案1】:

    使用time() 获取当前时间,使用difftime() 计算差异。

    #include <iostream>
    #include <ctime>
    #include <conio.h>
    using namespace std;
    int main()
    {
        int a,b;
        cout<<"enter 1";
        cin>>a;
        time_t atime = time(NULL);
        cout<<"enter 2";
        cin>>b;
        time_t btime = time(NULL);
        cout << difftime(btime, atime) << " seconds passed\n";
        getch();
        return 0;
    }  
    

    【讨论】:

    • @OrelEraki 我不同意。 OP 要求变量 a 和 b 的输入之间的时间间隔。如果atime 被提前一行获取,则等待a 的时间被计算在内。
    • @timaru 从哪里可以获得有关图书馆 ctime 和 time_t 的详细信息
    • 在 Google 上搜索。
    【解决方案2】:

    time(), difftime() 的分辨率为一秒。

    推荐的方法是使用chrono library (c++11)

    #include <chrono>
    
    // ...
    
    // take time 0
    auto Time0= chrono::system_clock::now();
    
    // do some work ...
    
    // take time 1
    auto Time1= chrono::system_clock::now();
    
    // print the diff (in this example: in milliseconds)
    auto Duration= chrono::duration_cast<chrono::milliseconds>(Time1 - Time0).count();
    cout << Duration << endl;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 2014-07-15
      • 2018-08-14
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多