同时运行多个功能?

Ada*_*dam 2 c++ time multithreading

这一定是一个问题很多,但我找不到我想要的东西.

想象一下:

  • 一个程序启动"你好,你叫什么名字?"
  • 你输入一个数字,它就是"你的名字不能是一个数字!"

你继续输入一个数字并继续得到这个错误,而在后台它只是跟踪程序运行了多长时间,通过每秒做一次n ++,无论文本/输入部分发生了什么.最终你可以输入类似"时间"的东西,然后它显示你在那里待了多久,在几秒钟内...

所以我的问题是:你到底该怎么做呢?让它们独立运行?

提前致谢!

编辑:我不是特别试图做这个计时的事情,这只是我能想出的关于独立运行函数的最简单的例子.

And*_*owl 9

您无需运行并行任务即可测量已用时间.C++ 11中的一个例子:

#include <chrono>
#include <string>
#include <iostream>

int main()
{
    auto t1 = std::chrono::system_clock::now();

    std::string s;
    std::cin >> s;
    // Or whatever you want to do...

    auto t2 = std::chrono::system_clock::now();
    auto elapsedMS =
        (std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1)).count()

    std::cout << elapsedMS;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

由于您似乎对并行启动多个任务的方式感兴趣,因此这是一个提示(同样,使用C++ 11):

#include <ctime>
#include <future>
#include <thread>
#include <iostream>

int long_computation(int x, int y)
{
    std::this_thread::sleep_for(std::chrono::seconds(5));

    return (x + y);
}

int main()
{
    auto f = std::async(std::launch::async, long_computation, 42, 1729);

    // Do things in the meanwhile...
    std::string s;
    std::cin >> s;
    // And we could continue...

    std::cout << f.get(); // Here we join with the asynchronous operation
}
Run Code Online (Sandbox Code Playgroud)

上面的例子开始一个长时间的计算,至少需要5秒钟,同时还要做其他事情.然后,最终,它调用get()未来对象与异步计算连接并检索其结果(如果尚未完成则等待它完成).