【发布时间】:2020-02-22 12:15:23
【问题描述】:
所以我创建了以下简单程序来测量在我的机器上创建进程或线程的平均时间:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
DWORD WINAPI ThreadFunc(void* data) {
return 0;
}
int main(int argc, char** argv) {
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
clock_t begin, end;
double cpu_time_used;
for(int i = 0; i <= 1000000;i++){
begin = clock();
CreateProcess(NULL, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
end = clock();
cpu_time_used += ((double) (end - begin)) / CLOCKS_PER_SEC;
TerminateProcess(pi.hProcess, 0);
}
/* since we're running 1 000 000 (1 million) times we divide by 1
* million and since to get the time in ns instead of ns we multiply by
* 1 billion we simply multiply by 1000 since 1 billion / 1 million = 1000.
*/
printf("Average time to create a process = %f ns\n", cpu_time_used * 1000);
cpu_time_used = 0;
for(int i = 0; i < 1000000;i++){
begin = clock();
CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
end = clock();
cpu_time_used += ((double) (end - begin)) / CLOCKS_PER_SEC;
}
/* since we're running 1 000 000 (1 million) times we divide by 1
* million and since to get the time in ns instead of ns we multiply by
* 1 billion we simply multiply by 1000 since 1 billion / 1 million = 1000.
*/
printf("Average time to create a Thread = %f ns\n", cpu_time_used * 1000);
return (EXIT_SUCCESS);
}
以下结果:
Average time to create a process = 89.000000 ns
Average time to create a Thread = 112055.000000 ns
创建一个进程的时间似乎很合理,但为什么创建一个线程的时间比创建一个全新的进程要长一千倍呢?
【问题讨论】:
-
由于您将空的
lpApplicationName和lpCommandLine参数都传递给CreateProcess,因此无需运行任何内容,也无需创建进程。所以它什么也没做。 -
您的计时计算也存在缺陷...
clock函数不会为您提供 Windows 中经过的 CPU 时间(使用 VS CRT),它会为您提供 墙时钟 计时。所以你计算的时间还包括创建线程运行和主线程休眠的时间。 -
clock() 并没有按照你想象的方式工作。请改用 QueryPerformanceCounter()。
-
“可执行文件中调用 C 运行时库 (CRT) 的线程应使用 _beginthreadex 和 _endthreadex 函数进行线程管理”(来源 docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/…)。完全没有 C 运行时你不可能做任何事情,所以我的选择是安全而不是抱歉并使用它们。
标签: c windows multithreading