Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么我在VirtualBox中的多线程程序不比我的单线程程序快?_C_Multithreading_Operating System_Montecarlo_Pi - Fatal编程技术网

C 为什么我在VirtualBox中的多线程程序不比我的单线程程序快?

C 为什么我在VirtualBox中的多线程程序不比我的单线程程序快?,c,multithreading,operating-system,montecarlo,pi,C,Multithreading,Operating System,Montecarlo,Pi,大家好! 我有两个使用蒙特卡罗技术估算PI的程序:一个使用单线程,另一个使用多线程 单线程的一个: #include <stdio.h> #include <stdlib.h> #include <time.h> #define BILLION 1000000000.0 int main(int argc, char *argv[]) { struct timespec start, end; ///////////////////////

大家好! 我有两个使用蒙特卡罗技术估算PI的程序:一个使用单线程,另一个使用多线程

单线程的一个:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BILLION 1000000000.0

int main(int argc, char *argv[])
{
    struct timespec start, end;
    ///////////////////////
    clock_gettime(CLOCK_REALTIME, &start);
    ///////////////////////
    if(argc != 2)
    {
        fprintf(stderr, "usage: a.out <integer value>\n");
        return -1;
    }
    
    if(atoi(argv[1]) < 0)
    {
        fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
        return -1;
    }
    time_t t;
    srand((unsigned) time(&t));
    int total = atoi(argv[1]);
    int inside = 0;
    unsigned int seed = rand()%30000;
    for(int i = 0; i < total; ++i)
    {
        double rand_x = (double)rand_r(&seed)/(double)RAND_MAX;
        double rand_y = (double)rand_r(&seed)/(double)RAND_MAX;
        
        double dist = rand_x*rand_x + rand_y*rand_y;
        if(dist < 1.0) ++inside;
    } 
   
    double pi = (double)(4 * inside)/total;
    clock_gettime(CLOCK_REALTIME, &end);
    double time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / BILLION;
    printf("pi = %lf\n", pi);
    printf("time = %f\n", time_spent);
    return 0;
}
多线程输出:

quan@quan-VirtualBox:~/Documents/lab5$ ./pi_multi-thread 100000000
pi = 3.141532
time = 1.446410

注意:有时多线程的速度甚至比单线程的慢


有什么问题吗?我认为多线程必须比单线程有一些速度提升。我的多线程代码错了吗?请给我一些建议?谢谢大家!

你在一个VirtualBox上运行。您是否启用了多核?谢谢!这正是我的问题!启用多核后,多线程的速度会更快!
quan@quan-VirtualBox:~/Documents/lab5$ ./pi_serial 100000000
pi = 3.141583
time = 1.576207
quan@quan-VirtualBox:~/Documents/lab5$ ./pi_multi-thread 100000000
pi = 3.141532
time = 1.446410