用一個簡單的 numpy å°ç¨‹å¼ï¼Œå’Œä¸€å€‹ C å°ç¨‹å¼ï¼ŒåŸ·è¡ŒåŸºæœ¬çš„陣列é‹ç®—,來測試 numpy å’Œ C 的執行速度。
- numpy 程å¼
#! /usr/bin/env python # -*- coding: UTF-8 -*- import sys import time import codecs from Numeric import * if __name__ == '__main__': loopnum = 10000000 sys.stdout.write( "Constructing numpy double array (length %d)...\n" % loopnum ) now = time.time() a = arange(loopnum).astype(Float64) sys.stdout.write( " for %f secs.\n" % (time.time() - now) ) sys.stdout.write( "python double array calculating...\n" ) now = time.time() b = a + a sys.stdout.write( " for %f secs.\n" % (time.time() - now) )
- C ç¨‹å¼ (請使用 gcc -c test test.c -lrt,進行編è¯ï¼Œä»¥ç¢ºä¿ clock_gettime() 會被連çµé€²å¯åŸ·è¡Œæª”)
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int i; int loopnum = 10000000; double j; double *a; struct timespec *now; now = (struct timespec *)malloc(2*sizeof(struct timespec)); printf("Constructing C double array (length %d)...\n", loopnum); clock_gettime(CLOCK_REALTIME, now); a = (double *)malloc(loopnum*sizeof(double)); for (i=0; i<loopnum; i++){ a[i] = 0.0; } clock_gettime(CLOCK_REALTIME, now+1); printf( " for %f secs.\n", ( (now+1)->tv_sec - now->tv_sec ) + ( (now+1)->tv_nsec - now->tv_nsec ) * 1.e-9); printf("C double array calculating...\n"); clock_gettime(CLOCK_REALTIME, now); for (i=0; i<loopnum; i++){ j = a[i] + a[i]; } clock_gettime(CLOCK_REALTIME, now+1); printf(" for %f secs.\n", ( (now+1)->tv_sec - now->tv_sec ) + ( (now+1)->tv_nsec - now->tv_nsec ) * 1.e-9); }
在 Xeon 550 ä¸Šçš„åŸ·è¡Œçµæžœæ˜¯:
- numpy 程å¼
Constructing numpy double array (length 10000000)... for 3.299104 secs. python double array calculating... for 2.623237 secs.
- C 程å¼
Constructing C double array (length 10000000)... for 0.576618 secs. C double array calculating... for 0.741613 secs.
numpy 的計算速度比 C 慢了大約 3.5 å€ï¼›é™£åˆ—的建立速度則慢了大約 5.7 å€ã€‚
æ ¹æ“šé€™å€‹çµæžœï¼Œå¦‚果想用 Python 開發計算程å¼ï¼Œå¯¦ç”¨ä¸Šä¸€å®šè¦ç‚ºè¨ˆç®—æ ¸å¿ƒæ’°å¯« C module,å¦å‰‡å…¶é€Ÿåº¦å°‡æ˜¯ä¸å¯æŽ¥å—的。
Navigate
- Previous: ã’ã‚“ã—ã‘ã‚“ 第三話 地域文化振興ã®å•題点ã¨ãã®åŠŸç¸¾ @2004/11/01
- Next: å‰¯æª”åæ¸¬é©— @2004/11/03
Add a trackback
Please send trackback to: http://blog.seety.org/everydaywork/2004/11/2/62/trackback/.
Comments
Re: 在陣列的處ç†é€Ÿåº¦ä¸Šï¼Œnumpy é æ¯” C æ…¢
您說的極是,後來我也注æ„到了這個å•題,所以儘é‡ç”¨ atomic operation。
yungyuc
at 2007-08-25 21:12.
Add a comment
æ¤æ—¶é€Ÿåº¦å·®å¼‚ä¸å¤§ã€‚